Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
54
rated 0 times [  55] [ 1]  / answers: 1 / hits: 18328  / 12 Years ago, wed, june 27, 2012, 12:00:00

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);
});

More From » jquery

 Answers
22

Important: Use $(document).bind('pageinit'), not $(document).ready()



The first thing you learn in jQuery is to call code inside the
$(document).ready() function so everything will execute as soon as the
DOM is loaded. However, in jQuery Mobile, Ajax is used to load the
contents of each page into the DOM as you navigate, and the DOM ready
handler only executes for the first page. To execute code whenever a
new page is loaded and created, you can bind to the pageinit event.
This event is explained in detail at the bottom of this page.




I was trying to bind using document ready instead of pageinit. The first function



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


works fine when moved to the 'pageinit' event. I am still not sure, however, why the second code example worked but not the first.


[#84629] Tuesday, June 26, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sheylap

Total Points: 141
Total Questions: 99
Total Answers: 99

Location: Sint Maarten
Member since Tue, Mar 29, 2022
2 Years ago
;