Reputation: 275
I want to show a div under input field when user click/focus a input field and hide the div when focus is out or User clicks outside the div or input field. In this fiddle example, when i click input, a div is shown and when i click outside the input field it gets hidden.
But i want to keep the div visible in below conditions :
1. When input is focused/clicked.
2. When click is within the div(.options).
The div should be hidden when:
1. Input is unfocused and click in not within div.
2. Click outside div.
Upvotes: 1
Views: 373
Reputation: 263
make sure the body tag contains your app and it's full width and height of the window. add en event listener to see if the click event is outside of the options div and not the input field. hide the options div if that is the case.
body {
height: 100vh;
width: 100%;
}
$(function () {
var inputField = $('#input_field');
var optionsResult = $('#options');
var options = document.querySelector('#options');
// Listen for click events on body
document.body.addEventListener('click', function (event) {
// hide options if click is outside of options div and not the input element
if (!options.contains(event.target) && event.target.id !== 'input_field') {
optionsResult.hide();
}
});
inputField.focusin(function (e) {
e.preventDefault();
optionsResult.show();
});
});
Upvotes: 2
Reputation: 68923
You can try using relatedTarget
like the following way:
$(function () {
var inputField = $('#input_field');
var optionsResult = $('#options');
inputField.focusin(function (e) {
e.preventDefault();
optionsResult.show();
}).focusout(function (e) {
if(e.relatedTarget){
if(e.relatedTarget.tagName != 'A')
optionsResult.hide();
}
else{
optionsResult.hide();
}
});
});
$(document).on('click', function(e){
if(e.target.tagName == 'HTML'){
$('#options').hide();
}
});
.options{
display:none;
position: absolute;
float: left;
width: 300px;
height: 200px;
background: #eee;
}
a{
display:block;
float: left;
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="app">
<div class="header">
<div id="main_container" class="box">
<div class="inputs">
<input id="input_field" type="text" placeholder="Demo account"/>
</div>
<div id="options" class="options">
<a href="#">Common Link</a>
<a href="#">Common Link 2 </a>
</div>
</div>
</div>
<div class="Data">
Another Data Set
</div>
</div>
Upvotes: 2