Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Click event on div but not on checkbox in the div

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
})
like image 525
Ryan Avatar asked Jan 11 '10 18:01

Ryan


2 Answers

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

$('.checkboxInTheDiv').click( function(e) {
    e.stopPropagation();
    ... other stuff...
    return true;
});
like image 73
tvanfosson Avatar answered Nov 02 '22 07:11

tvanfosson


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.

like image 34
Topher Fangio Avatar answered Nov 02 '22 08:11

Topher Fangio