1

I'm creating a mobile site for a client and I need to create a function to show and hide a DIV element when a button(a tag) is pressed. This is my code:

<script type="text/javascript">
$('#wrapper').live( 'pageinit',function(event){
  $("#btnInfo").click(function(){
      $("#pageInfo").toggle();
  });
});
</script>  

What happens is: When the page loads and i press btnInfo, the div shows up, works like it should but then i press on a link to go to the next page but on that page it does not show up anymore, whenever when i go back to the page i loaded at first it still works. I think this is because the page is loaded in AJAX, which i want it to be. I searched for a fix and i found: http://jquerymobile.com/test/docs/api/events.html and jQuery Mobile - binding to pageinit event tried it both, and the alert shows up when i switch pages but the function i wrote does not work

what do i do wrong?

Greetings, Harm.

Community
  • 1
  • 1
Hawiak
  • 553
  • 1
  • 9
  • 32

3 Answers3

3

The click method needs to be attached via .on() to the element that is being appended on-the-fly.

$("#btnInfo").on('click', function() {
    $("#pageInfo").toggle();
});
Labu
  • 2,572
  • 30
  • 34
  • Thanks. I answered this before `on()` existed in the API. I've updated my answer, but I see Saurabh already got there. :) – Labu Jan 18 '14 at 11:34
2
$( "#btnInfo" ).on( "click", function( event ) {
          $("#pageInfo").toggle();
});
Saurabh Chandra Patel
  • 12,712
  • 6
  • 88
  • 78
-1

Try this:

$("#btnInfo").bind('click',function(){
          $("#pageInfo").toggle();
      });
Wouter Dorgelo
  • 11,770
  • 11
  • 62
  • 80
phpcxy
  • 1
  • 3
  • Tried that, and it didnt work... Thanks for your help though. Code: $('#wrapper').live( 'pageinit',function(event){ $("#btnInfo").bind('click',function(){ $("#pageInfo").toggle(); }); }); – Hawiak Apr 02 '12 at 13:12