Ramesh Paul
Ramesh Paul

Reputation: 850

jQuery hide div clicking outside div excluding its child div

I have one div(sel_optn1) and i am showing sel_optn1 on click of li(opt1) and hiding sel_optn1 out side click of sel_optn1.
It is working fine but if i click on children of sel_optn1 it is hiding.

I want to hide sel_optn1 only on out side click, but to exclude sel_optn1 children's click from hiding sel_optn1

see this example which i am trying http://jsbin.com/ahuyak/1/edit

Can any one help me achieving this.

Upvotes: 0

Views: 2742

Answers (6)

voigtan
voigtan

Reputation: 9031

I bound the click event on the document and check if the target that was clicked on is the .sel_optn1 and then i bound the click event on the document and check its target if its .sel_optn1 or any of its children, dont hide it:

$(document).ready(function(){
  var option = $(".sel_optn1");

  $("#opt1").click(function(e){
    e.stopImmediatePropagation();
    option.toggle();
  });

  $(document).click(function(e){
    var target = $(e.target);
    if(!(target.is(option) || option.find(target).length)){
      option.hide();
    }
  });
});

and a demo: http://jsbin.com/ahuyak/15/

Upvotes: 0

kayen
kayen

Reputation: 4868

Update your check function to check clicks on its child elements as well:

if(e.target.className !== "sel_optn1" && !$(e.target).parents('.sel_optn1').length)

Upvotes: 4

Jai
Jai

Reputation: 74738

You can try blur instead: http://jsbin.com/ahuyak/12/edit

$(document).ready(function(){
   $("#opt1").click(function(e){
     $('.sel_optn1 , :text').show();
     e.stopPropagation();
   });

   $('.sel_optn1 > :text').blur(function(e){
      $('.sel_optn1 , :text').hide();
      e.stopPropagation();
   });
});

Upvotes: 0

zdesam
zdesam

Reputation: 2976

Check this

http://jsbin.com/ahuyak/11/edit

You have to check all the child elements

Upvotes: 0

Rajiv007
Rajiv007

Reputation: 1136

div(sel_optn1).children().click(function(){stopPropagation ( );})

Upvotes: 0

Musa
Musa

Reputation: 97672

Just check if the click target was in the element

if(e.target.className !== "sel_optn1" && !$.contains($(".sel_optn1")[0], e.target))
{
    $('.sel_optn1').css({"display":'none'});
}

Upvotes: 0

Related Questions