Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want JQuery to ignore click on a particular child element

Tags:

jquery

I've delcared a click callback on a div that I would like ignored if a user clicks on a link inside that div. The function looks like this:

$(".section").click(function(){
    if ($(this).hasClass("solid")) {
        $(this).removeClass("solid");
        $(this).hover(fadeFunction, darkenFunction);
        $(this).fadeTo(150, inactiveOpacity);
    }
    else {
        $(this).addClass("solid");
        $(this).unbind("mouseenter");
        $(this).unbind("mouseleave");
        $(this).fadeTo(25, inactiveOpacity);
        $(this).fadeTo(150, activeOpacity);
    }
});

I've tried wrapping the if/else up in a if(!$(this).is("a)) { but there is no change in behavior. Can somebody point out what I'm misunderstanding or doing wrong?

Sorry if this is an easy question, I'm a JQuery/css beginner.

like image 592
Rich Avatar asked Nov 22 '25 09:11

Rich


2 Answers

You can check if the event target is an anchor, like this:

$(".section").click(function(e){
    if($(e.target).is("a")) return;

    if ($(this).hasClass("solid")) {
        $(this).removeClass("solid");
               .hover(fadeFunction, darkenFunction);
               .fadeTo(150, inactiveOpacity);
    }
    else {
        $(this).addClass("solid");
               .unbind("mouseenter mouseleave");
               .fadeTo(25, inactiveOpacity);
               .fadeTo(150, activeOpacity);
    }
});
like image 151
Nick Craver Avatar answered Nov 24 '25 22:11

Nick Craver


Try this:

$('a').click(function(e) {
    e.stopPropagation();
});

Here you can find documentation: http://api.jquery.com/event.stopPropagation/

like image 20
davehauser Avatar answered Nov 24 '25 22:11

davehauser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!