1

Here's my situation:

I have a custom menu on right mouse click for my project. Here, I have document.addEventListener on click, that makes this menu invisible, like this:

var i = document.getElementById("menu").style;
document.addEventListener('click', function(e) {
    i.opacity = "0";
    setTimeout(function() {
        i.visibility = "hidden";
    }, 100);
}, false);

And it's great, works well, but I'm implementing a dropdown submenu that should be opened when you click on a certain element, like so:

 $('#change_color').click(function(){
      if($('#back_color').hasClass('back_color')){
           $('#back_color').removeClass('back_color')
      }else{
           $('#back_color').addClass('back_color')
      }
 })

The thing is that when I click on that #change_color then addEventListener is firing, which is obvious.

The question is – how can I prevent that listener function to execute when I click on #change_color?

1 Answer 1

4

You can prevent further propagation of the current event in the capturing and bubbling phases using event.stopPropagation() and for simplicity in your code use jQuery.toggleClass().

Code example:

$('#change_color').click(function (e) {
  $('#back_color').toggleClass('back_color');
  e.preventDefault();
  e.stopPropagation();
});
Sign up to request clarification or add additional context in comments.

1 Comment

@МаркЧолак Updated the answer according to your comment.. Thanks

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.