1

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.

3 Answers 3

4

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();
});
Sign up to request clarification or add additional context in comments.

2 Comments

could he also change his second click handler so that it's not attached to the 'document' but to element with the class '.scrolls' instead?
@GeorgeKatsanos No, because he's adding the scrolls class dynamically, so he has to use delegation. So the element won't have the class when he binds the click handler.
0

It seems you may not want to add the handler until the first click?

$('.service-blurb').click(function() {
    $(this).addClass('scrolls');
    $(this).off('click'); // Disable this handler now that we're done

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

1 Comment

It's still triggering the second click automatically :/
0

If I understood right, you need event.preventDefault().

$('.service-blurb').click(function(e) {
    $(this).addClass('scrolls');
    e.preventDefault;
});

For more... check here... https://api.jquery.com/event.preventdefault/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.