Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blur function not working

I am trying to use blur function, however, its not working. I want to hide the div if user clicks outside.

<div id="container">
Links
</div>

$(document.body).on('blur', '[id="container"]' ,function(){
$("#container").hide();
});

What is the correct way ?

like image 748
caner taşdemir Avatar asked Jun 17 '26 19:06

caner taşdemir


1 Answers

This is the issue:

  1. document.body should be document.
  2. [id="container"] should be #container. Better selector.
  3. The <div /> doesn't have a blur event. So use click event instead of blur.

The tabindex way:

Giving the attribute tabindex enables the element to have blur and focus events. Now giving blur on it will work.

Snippet

$(document).on('blur', '#container' ,function(){
  $("#container").hide();
});
#container {height: 100px; background: #ccc;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container" tabindex="1">Click Me and Outside Me</div>
like image 73
Praveen Kumar Purushothaman Avatar answered Jun 19 '26 08:06

Praveen Kumar Purushothaman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!