4

I've got something like this http://jsfiddle.net/4bzvp7o2/ and I want to exclude the #bar element from participating in the toggle function when clicked.

So if one clicks on the blue part when it is visible, nothing will happen, I have tried...

$('#foo').not('#bar').click(function ()
2
  • $('#foo:not(#bar)').click() will solve the issue? I checked on stackoverflow website and it works. so I'm adding it as an answer. Commented Oct 13, 2015 at 9:34
  • tried with no luck jsfiddle.net/4bzvp7o2/3 Commented Oct 13, 2015 at 9:40

4 Answers 4

5

See your case is very useful to know about event bubbling. When you have an event which is bound on parent element which in your case is $('#foo') to do something when clicked and sometimes people need to do something else to do on child elements when clicked which in your case is $('#bar').

When you click an element which is deep down in the DOM heirarchy then the event happend on it will traverse up to all the parent nodes.

You need to have event.stopPropagation() to stop the event bubbling to the parent node:

$(document).ready(function() {
  $('#foo').click(function() {
    $('#bar').toggle('fast')
  });
  $('#bar').click(function(e) {
    e.stopPropagation(); // stops the event to bubble up to the parent element.
  });
})
#foo {
  width: 100px;
  height: 100px;
  background-color: yellow;
}
#bar {
  width: 50px;
  height: 50px;
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='foo'>
  <div id='bar'>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

2

Codepen http://codepen.io/noobskie/pen/jbLerX

You need to use e.stopPropagation();

$(document).ready(function() {
  $('#foo').click(function() {
    $('#foo').find('#bar').toggle('fast')
  })
  $('#bar').click(function(e) {
    e.stopPropagation();
  });
})

Comments

2

You can check the click target element and not fire toggle if target element is bar. See following code snippet.

    $('#foo').click(function (e) {
        if(!$(e.target).hasClass("bar")){
            $('#foo').find('#bar').toggle('fast');
        }
    });

You can also see this fiddle.

Comments

0

One way of doing it: http://jsfiddle.net/4bzvp7o2/2/

$(document).ready(function () {
    $('#foo').on('click', function (evt) {
        if (evt.originalEvent.target.id === 'bar') {
            return false;
        }
        $('#foo').find('#bar').toggle('fast');
    })
})

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.