Javascript to detect whether the dropdown of a select element is visible

11,171

Solution 1

here is how I would preferred to do it. focus and blur is where it is at.

<html>
    <head>
        <title>SandBox</title>
    </head>
    <body>
        <select id="ddlBox">
            <option>Option 1</option>
            <option>Option 2</option>
            <option>Option 3</option>
        </select>
        <div id="divMsg">some text or whatever goes here.</div>
    </body>
</html>
<script type="text/javascript">
    window.onload = function() {
        var ddlBox = document.getElementById("ddlBox");
        var divMsg = document.getElementById("divMsg");
        if (ddlBox && divMsg) {
            ddlBox.onfocus = function() {
                divMsg.style.display = "none";
            }
            ddlBox.onblur = function() {
                divMsg.style.display = "";
            }
            divMsg.style.display = "";
        }
    }
</script>

Solution 2

Conditional-content, which is what you're asking about, isn't that difficult. The in the following example, I'll use jQuery to accomplish our goal:

<select id="theSelectId">
  <option value="dogs">Dogs</option>
  <option value="birds">Birds</option>
  <option value="cats">Cats</option>
  <option value="horses">Horses</option>
</select>

<div id="myDiv" style="width:300px;height:100px;background:#cc0000"></div>

We'll tie a couple events to show/hide #myDiv based upon the selected value of #theSelectId

$("#theSelectId").change(function(){
  if ($(this).val() != "dogs")
    $("#myDiv").fadeOut();
  else
    $("#myDiv").fadeIn();
});
Share:
11,171
Ikoy
Author by

Ikoy

Updated on June 30, 2022

Comments

  • Ikoy
    Ikoy almost 2 years

    I have a select element in a form, and I want to display something only if the dropdown is not visible. Things I have tried:

    • Watching for click events, where odd clicks mean the dropdown is visible and even clicks mean the dropdown isn't. Misses other ways the dropdown could disappear (pressing escape, tabbing to another window), and I think this could be hard to get right cross-browser.
    • Change events, but these only are triggered when the select box's value changes.

    Ideas?

  • PetersenDidIt
    PetersenDidIt over 14 years
    This will work correctly for both mouse user and keyboard only users.
  • user3167101
    user3167101 almost 14 years
    You can make it more succinct with $element.is(':visible')