user2666310
user2666310

Reputation: 103

jquery toggle and hide on click outside

I had the follwing which worked fine

HTML:

<button class="btn btn-primary">Click</button>

<div class="text" style="display:none">Some text</div>

jQuery:

$(".btn").click(function(e){
  $(".text").fadeToggle('fast');
}); 

then I added the below to hide the text when clicked outside and now the toggle function isn't working, meaning it fades in when I click then if I click again it doesn't fade out permanently it just fades out and instantly it fades in again. is there anyway to combine these two functions?

$(document).mouseup(function (e){
  var container = $(".text");

  if (!container.is(e.target) // if the target of the click isn't the container...
      && container.has(e.target).length === 0) // ... nor a descendant of the container
  { 
    container.hide();
  }
});

Upvotes: 1

Views: 1152

Answers (2)

user2666310
user2666310

Reputation: 103

simple fix just added the btn class to be ignored too...

var x_con = $('.btn');
if (!container.is(e.target) // if the target of the click isn't the container...
    && container.has(e.target).length === 0 && !x_con.is(e.target)) // ... nor a descendant of the container
{
    container.hide();
}

Upvotes: 1

doniyor
doniyor

Reputation: 37904

this is working now:

$(".btn").click(function(e){
  $(".text").fadeToggle('fast');
});

$(document).on('mouseup', function(e) {
   if(!$(e.target).closest('.text').length) {
     $('.text').each(function(){
         $(this).hide();
     });
   }
});

demo: http://jsfiddle.net/LKhV5/

Upvotes: 2

Related Questions