I want to move the Div-element "nav", when a li-element was clicked.
I have a List in a div
<div id="nav">
<ul>
<li><a href="#t1">Flyer</a></li>
<li><a href="#t2">Code</a></li>
<li><a href="#t3">Angebot</a></li>
<li><a href="#t4">Bilder</a></li>
</ul>
</div>
Why doesnt this work in jquery:
$("#nav ul li").click(function(){
$("#nav").animate({
marginLeft: "-300px",
}, 1000 );
});
The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.
You can get the current clicked element using event. target . // click event for li $("#myid li"). click(function(){ alert("li clicked"); }); // click event for p $("#myid li p").
To trigger the onclick function in jQuery, click() method is used. For example, on clicking a paragraph on a document, a click event will be triggered by the $(“p”). click() method. The user can attach a function to a click method whenever an event of a click occurs to run the function.
The onclick event occurs when the user clicks on an element.
Depending on what version of Jquery you are using this may or may not work:
$('body').on('click', '#nav ul li', function(){
$("#nav").animate({
marginLeft: "-300px",
}, 1000 );
});
I did $('body') because if you are generating these li's dynamically then you need to bind 'delegated events' as they're called.
The code works fine as you expect, view the JSFiddle.
I have a feeling your forgetting something like putting it in the jQuery DOM Ready event.
Make sure you code looks like this (inside the DOM Ready)
$(document).ready(function(){ // When the DOM is Ready, then bind the click
$("#nav ul li").click(function(){
$("#nav").animate({
marginLeft: "-300px",
}, 1000 );
});
});
Make sure you have no other javascript errors on your page (If you do before this code, the code will not work), Check your console (In chrome right click > Inspect Element > console).
One of these 2 issues are causing your problems (most likely), else you will have to debug it yourself (or show us more code).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With