tags:

views:

48

answers:

2

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.

+3  A: 

Try this:

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

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

Dave
This is the right approach, but you may want to confine it to links within the specified div, rather than all links, e.g. `$("div.section a").click(...`.
JacobM
Yes, you're right, I meant it as a common approach (+1)
Dave
Keep in mind that this is a much more expensive approach, it's cheaper to add a if check *when* an event happens rather than bind `n` event handlers unnecessarily :)
Nick Craver
Yeah, I already noticed, you're the jQuery hero here on SO :D So, I take my hat off to you and give you +1 for this comment :)
Dave
@Dave - It's definitely a valid approach if you have a few links, just something to keep in mind if you have an unknown or large number is all :)
Nick Craver
+4  A: 

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);
    }
});
Nick Craver
Thanks Nick Craver!
Rich