melvindidit
melvindidit

Reputation: 440

Exclude a checkbox from .click() of a div

I'm tryin to make a div 'active' by clicking on it using jquery. But inside the div, there is a checkbox. I want the div to become active whenever i click anywher inside the div except the checkbox. I have done that, but the checkbox is now not responsding to click events (ie it's not getting checked/unchecked when i click on it).

http://jsfiddle.net/U7VmV/3/

 $(document).ready(function(){
    $('.c-video').click(function(){
        $('.c-video').removeClass('active');
        $(this).addClass('active');
    });
}).children().find('label').click(function(e){
    return false;
});

Upvotes: 3

Views: 1047

Answers (3)

dfsq
dfsq

Reputation: 193261

Another way to do it is to check clicked event target:

var $cVideo = $('.c-video').on('click', function(e) {
    if (e.target.tagName != 'INPUT' && e.target.tagName != 'LABEL') {
        $cVideo.removeClass('active');
        $(this).addClass('active');
    }
});

http://jsfiddle.net/U7VmV/4/

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

You have to prevent the propagation of the event, when you return false it prevents the event propagation but it will also prevents the default action of the click event that is checking/unchecking the checkbox.

So instead or returning false call stopPropagation() in the event object

$(document).ready(function(){
    $('.c-video').click(function(){
        $('.c-video').removeClass('active');
        $(this).addClass('active');
    });
}).children().find('label').click(function(e){
    e.stopPropagation()
});

Demo: Fiddle

Upvotes: 1

Use event.stoppropagation()

Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

}).find('label').click(function (e) {
    e.stopPropagation();
});

Fiddle Demo

Upvotes: 4

Related Questions