How to check that panel is visible or not in JavaScript?

asp.net, javascript

Solution

Assuming that you are setting the panel's visibility on the server-side, a check of the value returned by `document.getElementById()` will work, provided you ensure that you're using the the correct client ID of the panel control (don't hard-code it).

See the check in the client-side `findPanel()` function for a demonstration.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function findPanel() {
            var panel = document.getElementById("<%= pnlMyPanel.ClientID %>");
            if (panel) {
                alert("Panel is visible");
            }
            else {
                alert("Panel is not visible");
            }

//        // And this would work too:
//        alert((<%= pnlMyPanel.Visible.ToString().ToLower() %>) ? "Panel is visible": "Panel is not visible");

        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Panel runat="server" ID="pnlMyPanel">
            <p>
                This is a panel.</p>
        </asp:Panel>
        <asp:Button runat="server" ID="btnToggle" Text="Toggle panel visibility..." />
        <input type="button" value="Do client-side visibility check..." onclick="javascript:findPanel();" />
    </div>
    </form>
</body>
</html>

The following code in the code-behind file toggles the panel's visibility when `btnToggle` is clicked:

protected void Page_Load(object sender, EventArgs e)
{
    btnToggle.Click += new EventHandler(btnToggle_Click);
}

void btnToggle_Click(object sender, EventArgs e)
{
    pnlMyPanel.Visible = !pnlMyPanel.Visible;
}

Problem

How do I check that panel is visible or not in JavaScript?. I am using ASP.NET 2.0.

Original source

Related problems