Juan Bonnett Juan Bonnett - 1 year ago 95
jQuery Question

jQuery - Add a click handler after addClass

I have added a class to an element when user clicks it:

$('.service-blurb').click(function() {

Now I want to add an event handler to the 'scrolls' class so when the user clicks again it scrolls.

$(document).on('click', '.scrolls', function() {
//scrolls nicely to that service description

As soon as I click the first time on the '.service-blurb' element, it not only adds the class but it also scrolls. I want it to scroll only when the user clicks for the second time.

Answer Source

What's happening is that the event is bubbling out to the document, and then it checks whether you clicked on an element that matches .scroll, so it runs the delegated handler.

Change the first handler so it stops event bubbling.

$('.service-blurb').click(function(e) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download