Google Maps Click Event jQuery .On()

I am integrating the google maps api into my application on the map it has an info window that will display information about a marker / cluster in that location. My problem is that when the map loads and I click on a cluster, the next button only works the first time the info window appears. Once I close the info window and open another info window by clicking on the cluster again, the $(‘next’) click event won’t fire. I find this to be odd because both times I am creating and destroying the next link element. What am I doing wrong? jquery’s on function isn’t working for me. Please help.

You can see a live example at pitchbig.com/people2.php

The code for the next event is in my people2.js file and is about half way down the page.


$("#next").on("click", function(){
   var toHighlight = $('.first').next().length > 0 ? $('.first').next() : $('#infoWin li').first();
   $(this).fadeOut(100);
   $('.first').fadeOut(100);
   $('.first').delay(100).removeClass('first');
   toHighlight.delay(100).addClass('first');
   $('.first').delay(100).fadeIn(100);
   $(this).delay(100).fadeIn(100);
});

You might need to delegate that event handler up to the parent (the map for example) as the “#next” button gets destroyed and created - it would be better if the event was delegated up.

e.g.


$("#highlight").on("click", "#next", function() {
  //do stuff
});

See http://jqapi.com/#p=on

That really helped and got the onclick event working, but now I think I just need to work out some other issues. The window flashed when I hit the next button in other windows. The event isn’t treated the same. Thanks for your help.

Ok so I think I’ve figure out what is going on now. My events are bubbling. If I open the window 3 times and click the next button respectively, on the forth time when I click the next button the next event will fire four times. How do I stop this?

To prevent events from bubbling you can call the .stopPropagation() method on the current event handler.

Like so (and be sure to pass the event variable as an argument to the event handler method):


$("#highlight").on("click", "#next", function(e) { // set a parameter name to address the event by

  // prevent the event from bubbling up
  e.stopPropagation();

  // do stuff

  // additionally if you wish to be sure that the default action
  // is not going to happen, you can call .preventDefault();
  e.preventDefault(); 

});

However, this may not be the actual problem here. You might want to double check that you only apply the event handler method once (and not, for example for each cluster).

See: