简体   繁体   中英

Fade out on click, unless input element is clicked on

The .container needs to fade out when the user clicks anywhere, but not when the user clicks in the input field.

Is there a way to make it fade out, unless the input field is clicked?

Fiddle

$('.container').click(function () {
    $(this).fadeOut();
});
<div class="container">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam eum ad adipisci velit assumenda cupiditate molestias facere officia neque maxime voluptatum officiis libero animi sit a accusamus culpa quasi quis!</p>
    <input type="text" name="" id="" autofocus />
</div>

Bonus points if it works on older browsers.

You need to stopevent propogating to textbox. Use this:

$(".container input").click(function(e) {
    e.stopPropagation();
})

Working Demo

You can use e.stopPropagation() to prevent click event to buble up when your input getting focus:

$('.container input').click(function (e) {
    e.stopPropagation();

});

Updated Fiddle

try this

$(".container input").click(function(event) {
    event.stopPropagation();
})

The other answers use stopPropagation , but it also works with return false;

$('.container input').click(function() {
   return false;
});
$('.container').click(function () {
  $(this).fadeOut();
});

wow..so many answers....try this one too...just use $(event.target) to find what was clicked on the body element and if its not the input, then toggle the container!! :)

solution fiddle

$('body').click(function(event) {
    if($(event.target).is('#input'))
    {}
    else
    {
        $('.container').toggle(1200);
    }

});

and add an id to <input type="text" name="" id="input" autofocus />

if not then , ammned to

if($(event.target).is('input'))      
                   /* ^^ removed # tag from here*/

demo without an id to input element

Yes, there is a way, see demo below.

$('.container').click(function (e) {
  if ($(e.target).closest("input[type='text']").length === 0) {
      $(this).fadeOut();
  }
});

DEMO

Or

$('.container').not('input').click(function () {...});

There are many posts like this...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM