Attach JQuery Click Event to Anchor Id

Jon Wells picture Jon Wells · Jun 27, 2012 · Viewed 17.5k times · Source

I have an easy one SO. Why cant I attach a click event straight to an anchors Id? I should have pointed out that I am also using JQuery Mobile.

            <div id="foobarNavbar" data-role="navbar" style="display:none;">
                <ul>
                    <li><a id="foo" href="#foo" data-icon="plus">New Event</a></li>
                    <li><a id="bar" href="#bar" data-icon="grid">Events</a></li>
                </ul>
            </div><!-- /foobarNavbar-->

I am trying to attach a click event to foo. This doesn't work:

        $('#foo').bind('click', function(e) 
        {   
            e.preventDefault();
            console.log("You clicked foo! good work");
        });

This does work but gives me the click event for both foo and bar. Is it not possible to bind to an anchor Id or am I making a rookie error?

        $('#foobarNavbar ul li a').bind('click', function(e) 
        {   
            e.preventDefault();
            console.log("You clicked foo! good work");
            console.log(e);
        });

Answer

Shyju picture Shyju · Jun 27, 2012

Wrap that code in the document ready and it should work if you dont have any other script errors and you have jQuery loaded.

$(function(){
   $('#foo').click(function(e) 
   {   
      e.preventDefault();
      console.log("You clicked foo! good work");
   });
});