I have a a textbox in my app, onkeyup
I show a div that gets result from database. so whenever user enters something I show the div, the problem is that I want to hide the div if users clicks somewhere else in the DOM.
just like when you select a drop down if you click somewhere else the drop down is closed.
Is there any builtin mechanism for this in jquery or javascript?
Asked
Active
Viewed 581 times
2

Community
- 1
- 1
4 Answers
1
$( "body" ).click(function() {
$( "#yourDivIdHere" ).hide();
});

LifeQuery
- 3,202
- 1
- 26
- 35
-
I have some elements on div too, If someone click on BODY, it hides the div. if someone clicks on elements inside the div, it also hides the div – Apr 28 '14 at 09:41
-
Then change `body` to whichever element you want. You can create a ` – LifeQuery Apr 28 '14 at 09:45
-
didn't get that at all – Apr 28 '14 at 10:37
-
@user1765876 give the div you want to hide an id `` and then use `$("#hideme")`– LifeQuery Apr 28 '14 at 11:20
0
Use event delegation and check the originator of a click event. Something like:
$('body').on('click',function (e) {
var origin = e.target || e.srcElement;
if (/* [origin.id != your dropdowndiv.id] */) {
/* hide your dropdowndiv */
}
});

KooiInc
- 119,216
- 31
- 141
- 177
0
Try this. Demo: http://jsbin.com/xatanicu/4/edit
$(document).ready(function() {
$('input').focusout(function() {
$(document).click(function(e) {
var targetId = $(e.target)[0].id;
if((targetId !== 'hide-div')) {
$('div').hide();
}
});
});
});

sap
- 343
- 3
- 11
-
-
focusout works if I click on any other area, but If I click on the div , it still hides the div then. – Apr 28 '14 at 09:38
-
just see this http://jsbin.com/xatanicu/5/edit , click on the button, 2- click somewhere else, 3- click on button again, it wont show the div, as it was showing in step 1 – Apr 28 '14 at 13:32
0
You can hide the result div when the textbox loses focus:
//vanilla JavaScript
textBoxId.onblur = divId.style.display = 'none';
//jQuery
$("#textBoxId").blur(function() {
$("#divId").hide();
});
UPDATE: It should not hide the result div if the user clicked on the result div itself. (The answer is based on Action on blur except when specific element clicked with jQuery)
var keepFocus = false;
function hideList(){
if(!keepFocus){
$('#divId').hide();
}
}
$('#textBoxId').blur(function() {
keepFocus = false;
window.setTimeout(hideList, 100);
}).focus(function(){
keepFocus = true;
});
$('#divId').blur(function() {
keepFocus = false;
window.setTimeout(hideList, 100);
}).click(function(){
keepFocus = true;
});
See this solution in action here: http://jsfiddle.net/XC2D7/
-
The advantage of this approach is that not only it works by clicking somewhere but it also works if user leaves the textBox by pressing 'Tab' on the keyboard. – advncd Apr 27 '14 at 08:17
-
-
@sap blur works if I click on any other area, but If I click on the div , it also hides the div then.. – Apr 28 '14 at 09:39