开发者

jQuery selector: Not this div and not that div

I am trying to create a jQuery click function that will close a div when you click on anything besides that div. My problem is that there is a search field and another button inside that div that need to stay open if you click on them.

My current functi开发者_StackOverflow社区on is:

$("*:not(#header)").click(function() {
    $('#header').slideUp({
        duration: 550, 
        easing: 'easeOutExpo'
    });
});

I want to also say "and is not '#categoryMore' and is not '#headerSearch'" but the syntax I've been using have not been working.

$("*:not(#header, #categoryMore, #headerSearch)")

and

$("*:not(#header), *:not(#categoryMore), *:not(#headerSearch)")

Any ideas? Thanks so much for your help!


EDIT:

Here's an example you can test. http://jsfiddle.net/yvFcz/

I used slideToggle() for the example so you can more easily test it more than once.


Put a handler on the document that closes #header.

Then place a handler on #header that does event.stopPropagation() to prevent the event from bubbling up to the document when you click inside it.

$(document).click(function() {
    $('#header:visible').slideUp({
        duration: 550, 
        easing: 'easeOutExpo'
    });
});

$('#header').click(function( event ) {
    event.stopPropagation();
});
  • http://api.jquery.com/event.stopPropagation

Note that if any other elements on the page has a click handler that uses event.stopPropagation() or return false;, the event won't bubble up to the document, and your #header won't close.

In that case, you would need to handle it directly in that handler.


There is a jQuery plugin jQuery outside events you might want to use:

With jQuery outside events you can bind to an event that will be triggered only when a specific “originating” event occurs outside the element in question. For example, you can click outside, double-click outside, mouse-over outside, focus outside (and over ten more default “outside” events). Also, if an outside event hasn’t been provided by default, you can easily define your own.


I think you can use jQuery not() and it might be as simple as this:

$(document).not('#header, #categoryMore, #headerSearch').click(function() {
    $('#header').slideToggle({
        duration: 550, 
        easing: 'easeOutExpo'
    });
});

This allows you to click anywhere outside of the #header and the action will be triggered. You don't have to worry about other .click() events and their propagation (at least not to my knowledge)... it will just NOT select #header, #categoryMore, and #headerSearch.

You can use jQuery slideToggle() to slide up and down the header and its content whenever you click outside of it. If you only want to hide it, then just use .slideUp() as you do now :)

Hope that helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜