Check if select is displaying options
You can try listening on click, blur and key press event. I am just toggling a open
variable to true or false
on each of the event.
// if menu is open then true, if closed then false
// we start with false
var open = false;
// just a function to print out message
function isOpen(){
if(open)
return "menu is open";
else
return "menu is closed";
}
// on each click toggle the "open" variable
$("#myselect").on("click", function() {
open = !open;
console.log(isOpen());
});
// on each blur toggle the "open" variable
// fire only if menu is already in "open" state
$("#myselect").on("blur", function() {
if(open){
open = !open;
console.log(isOpen());
}
});
// on ESC key toggle the "open" variable only if menu is in "open" state
$(document).keyup(function(e) {
if (e.keyCode == 27) {
if(open){
open = !open;
console.log(isOpen());
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="myselect">
<option selected>Test 1</option>
<option>Test 2</option>
<option>Test 3</option>
</select>
You can use change
event in case of not displayed
, and focus
event for displayed
$("#myselect").on({
"change": function() {
$(this).blur();
},
'focus': function() {
console.log("displayed");
},
"blur": function() {
console.log("not displayed");
},
"keyup": function(e) {
if (e.keyCode == 27)
console.log("displayed");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="myselect">
<option selected>Test 1</option>
<option>Test 2</option>
<option>Test 3</option>
</select>