Skip to content Skip to sidebar Skip to footer

Javascript To Detect Whether The Dropdown Of A Select Element Is Visible

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

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><selectid="ddlBox"><option>Option 1</option><option>Option 2</option><option>Option 3</option></select><divid="divMsg">some text or whatever goes here.</div></body></html><scripttype="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:

<selectid="theSelectId"><optionvalue="dogs">Dogs</option><optionvalue="birds">Birds</option><optionvalue="cats">Cats</option><optionvalue="horses">Horses</option></select><divid="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();
});

Solution 3:

My first question is - why are you trying to do this? I can't think of any application that exhibits this behavior and I can't think of a good reason for this situation to happen.

I'm not saying you don't have a good reason, but I just don't know what that might be :).

Solution 4:

I don't think there's direct support. You could also sit on the onblur of the select -- it gets called when the select loses focus.

Depending on how important it is, you could try implementing your own control or starting from one like a drop-down menu control which is similar. Usually, unless it's critical to your application, it's not worth doing this. If you decide to go this route, here's a discussion of someone trying to do it using dojo as a basis:

http://dojotoolkit.org/forum/dijit-dijit-0-9/dijit-support/emulating-html-select

Solution 5:

Keep track of the state using a JavaScript varialbe. We'll call it "openX".

onfocus="openX=true" onblur="openX=false" onchange="openX=false"

Post a Comment for "Javascript To Detect Whether The Dropdown Of A Select Element Is Visible"