Juan Bonnett Juan Bonnett - 22 days ago 5
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() {
$(this).addClass('scrolls');
});


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


THE PROBLEM:
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

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) {
    $(this).addClass('scrolls');
    e.stopPropagation();
});