0

I have a sidebar div that I want to be hidden on page load. I have tried calling a JS function using a register startup script in the pagerender as well as adding a "style="display:none;"". I currently have a the same JS call but on a control click, and it works fine... But I want the div to initially be hidden.

EDIT: using the prerender worked on localhost, but not on the server...

.aspx:

    <div id="mySidenav" class="sidenav">
        <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        Code...
        </asp:UpdatePanel>
    </div>

JS:

function openNav() {
        document.getElementById("mySidenav").style.width = "250px";
        document.getElementById("main").style.marginLeft = "250px";

    }

    function closeNav() {
        document.getElementById("mySidenav").style.width = "0";
        document.getElementById("main").style.marginLeft = "0";
        document.body.style.backgroundColor = "white";
    }

codebehind.vb:

Private Sub Page_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender
    ScriptManager.RegisterStartupScript(Me, Me.GetType(), "InitializePage", "InitializePage();", True)
    ScriptManager.RegisterStartupScript(Me, Me.GetType(), "closeNav", "closeNav();", True)
End Sub

Do you know of a way I can hide this div/close it on page load?

Dplusa25
  • 31
  • 2
  • 8
  • Why do you need server side code to be involved at all? – mason Apr 06 '17 at 19:23
  • @mason I would like to avoid doing that if I can. I am relatively new... – Dplusa25 Apr 06 '17 at 19:30
  • Involving the server when there's no need for it is a waste. `` putting that in your page will call the function when the page is done loading the DOM. See [this question](http://stackoverflow.com/questions/9899372/pure-javascript-equivalent-to-jquerys-ready-how-to-call-a-function-when-the). – mason Apr 06 '17 at 19:34
  • @mason like this? $(document).ready(function () { closeNav();}); – Dplusa25 Apr 06 '17 at 19:43
  • Ah, so you have jQuery? Yes, that will work, but you can make it even shorter. `$(function() { closeNav(); });`. I assumed you didn't have jQuery because you're using `document.getElementById('id')` instead of `$("#id")` – mason Apr 06 '17 at 19:45

1 Answers1

0

The easiest way would be to add the "closed" style attributes to the initial markup. That said, it would be better to put these properties in CSS and refer to them. See below for an example:

.navopen{
width: 250px;
margin-left: 250px;
}

.navClosed{
width: 0;
margin-left: 0;
}

And your JS would look like:

function openNav() {
        document.getElementById("mySidenav").className = "navOpen";
    }

    function closeNav() {
        document.getElementById("mySidenav").className = "navClosed";
    }

That may not be exact but should give you an idea

Simon
  • 764
  • 4
  • 8