J.C
J.C

Reputation: 752

Keeping a Div Visible or Hidden after postback in aspx using javascript

I have a div that can be open like on this picture with the button on the top right corner Div open

Or it can be closed like on this picture [Div Closed]

The problem is when I click on the editing pen in my GridView as you can see on the picture there is a postback causing the div to open again since it is the default value on page load.

Here is my pageLoad function in aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "showAndHideOnPageLoad", "InitalShowAndHide();", true);
    if (!IsPostBack)
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(), "showAndHideOnPageLoad", "InitalShowAndHide();", true);

    }
}

And here is the JavaScript for the hide and show div

function showAllFunction() {
    var y = document.getElementById("PageContent_btnExpandMenu");
    var z = document.getElementById("PageContent_btnCollapseMenu");
    var x = document.getElementById("PageContent_secondMenuContent");
    x.style.display = "block";
    y.style.display = "none";
    z.style.display = "block";
}
function hideAllFunction() {
    var y = document.getElementById("PageContent_btnExpandMenu");
    var z = document.getElementById("PageContent_btnCollapseMenu");
    var x = document.getElementById("PageContent_secondMenuContent");
    x.style.display = "none";
    y.style.display = "block";
    z.style.display = "none";
}   

Here are the important elements of the aspx page.

    <asp:ImageButton ID="btnCollapseMenu" ImageUrl="~/images/minimize.png" runat="server"  Width="20px" Height="20px"  OnClientClick="hideAllFunction(); return false;" CssClass="second-menu-icon"/>     
    <asp:ImageButton ID="btnExpandMenu" ImageUrl="~/images/maximize.png" runat="server"  Width="20px" Height="20px"  OnClientClick="showAllFunction(); return false;" CssClass="second-menu-icon"/>  

  <div ID="secondMenuContent" class="second-menu-show-style" runat="server"> 

My question is how can I keep it hidden or visible depending on the user choice after a postback is made. Any help would be appreciated.

Upvotes: 1

Views: 1081

Answers (1)

Pranay Rana
Pranay Rana

Reputation: 176956

Store hide/show value in in hidden field. and use that hidden field value to show/hide div. that will resolve your issue.

// 0 for hide
<asp:HiddenFieldID="hdnfldCurrentDateTime" value="0" runat="server" />  

function showAllFunction() {
   //access the value of hidden field or store value in hidden field and write logic for hide/show
}

Upvotes: 1

Related Questions