5

I'm trying to setup a click event on a div, and I would like that event to fire if that div is clicked anywhere except a checkbox in the div. If the checkbox is clicked, I do not want the div's click event to fire. I setup a click event on the checkbox and returned false, which stops the div's click event, but does not allow the checkbox to become checked either. Here's what I have now:

$('.theDiv').click(function() {
    // Click event for the div, I'm slide toggling something
    $('.sub-div', $(this)).slideToggle();
});

$('.checkboxInTheDiv').click(function() {
    // Do stuff for the checkbox click, but dont fire event above
    return false; // returning false won't check/uncheck the box when clicked
})

3 Answers 3

15

Instead of returning false, which prevents the default action, try just stopping propagation.

$('.checkboxInTheDiv').click( function(e) {
    e.stopPropagation();
    ... other stuff...
    return true;
});
Sign up to request clarification or add additional context in comments.

2 Comments

here's a good way to do the above: quirksmode.org/js/events_order.html
amazing. I was struggling with rewriting my html for a while. thanks!
3

You'll need to look at the event object passed into the click handler and see what type it is. Look at the Event.Type documentation for more information.

function handler(event) {
  var $target = $(event.target);
  if( $target.is("li") ) {
    $target.children().toggle();
  }
}

$("ul").click(handler).find("li > ").h

Note: Code copied from linked URL.

1 Comment

This answer is especially useful since it works even when the event is bound using the .live() method.
0

Try a simple return;

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.