Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Why does my click event on a li element not work?

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 );
});
like image 548
user2477311 Avatar asked Jul 11 '13 12:07

user2477311


People also ask

How do you fire a click event on an element?

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.

How do I know if Li is clicked?

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").

How can set click event in jQuery?

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.

Which event is run when an element is clicked?

The onclick event occurs when the user clicks on an element.


2 Answers

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.

like image 186
MonkeyZeus Avatar answered Oct 20 '22 06:10

MonkeyZeus


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).

like image 20
Anil Avatar answered Oct 20 '22 04:10

Anil