tags:

views:

56

answers:

1

Problem as in subject.

Sample:

<div id="trigger">click here</div>
<div id="slider"> content goes here: form elems, divs, spans, a etc. </div>

How do I do it so far:

    $(document.body).click(function(event){ 
        var target = $(event.target); 
          if (!target.is("#trigger") && !target.is("#slider") && [all elems in slider.div...]
}

What I try to accomplish:
Avoid listing all slider.div elems by id - if possible.
Allow one elem like div with id="close" inside of slider div to close it.

+2  A: 

This can be accomplished a number of ways, but my favorite is to name the trigger something like slider_1 and give it a class if .slider. Then give the actual slider an id of slider_1_content with a class if .slider_content. This will allow you to write something like:

$(".slider").click(function() {
    $("#" + this.attr("id") + "_content") ...
});

You can then assign a close class to your close buttons/links and force them to close the parent slider like:

$(".close").click(function() {
    $(this).closest(".slider_content").hide();
});
Chris Pebble
[ **`.closest()`** ](http://api.jquery.com/closest/) will, `"Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree."` OP's elements are **siblings** not descendants. ------ Also, if the parent is the slider, the button will disappear. You could use `.find()` for parent buttons and child sliders.
Peter Ajtai
the `.close` button/link would be a descendant not a sibling. The first piece of code I posted address the trigger/slider issue.
Chris Pebble
Precisely. If the `close` classed DIV is a descendant, then if you click on it, it will **disappear** (along with the slider contents)!! If it's not a descendant, then `closer()` won't work. Try it out ==> http://jsfiddle.net/tSTcL/ ---- PS: I don't get notified you commented back unless you start your message with `@Peter`. Only authors and editors of a post get automatic notification.
Peter Ajtai
As the OP describes it he wants a close button inside the slider that will close the slider when clicked. Since he wants the button to appear in the slider the button would logically be a descendant of the slider.
Chris Pebble
@Chris - The wording in the OP is somewhat unclear. I was inferring the meaning from the context and the title, `"prevent click inside div from closing it "` ------ Also, the sample HTML in the OP includes siblings..... But your guess is as good as mine ;)
Peter Ajtai
@Peter - I think you read this wrong, Chris has exactly what the OP asked for, a close button inside closes it (what *else* would a close button possibly do?).
Nick Craver
@Nick - Rereading the question, I think you and Chris are right. I'll probably delete my answer in a few days unless we hear back from Jeffz to the contrary.
Peter Ajtai