user3777369
user3777369

Reputation: 67

How to make my div load hidden before visibility is toggled

I have this jQuery code here that I'm planning to make a menu with that allows the user to toggle the visibility of it. However, I'm not not sure how I can load the page with the div hidden. I'm trying to make it so that it starts hidden, and can be shown by clicking a button, but instead, it starts visible.

My jQuery:

$(document).ready(function(){
  $("#nav").click(function(){
    $("#items").toggle();
  });
});

My HTML:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="nav"><a href="#"><p>Toggle</p></a></div>
<div id="items"><p>Content</p></div>

Upvotes: 0

Views: 2129

Answers (3)

wahwahwah
wahwahwah

Reputation: 3177

CSS:

#nav {
   visibility: hidden; /* if you want the element to occupy space but not be seen */
   display: none; /* if you want the element to not take up space */
}

You can also do this in-line HTML <div style="display:none;"></div>

To unhide:

$("#nav").show(); // for display: none;
$("#nav").css('visibility', 'visible'); // for visibility : hidden;

And, a Fiddle

Upvotes: 2

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93631

If you want something that is non-JavaScript compatible too, I use a jshidden style on the elements and style them out based on a class added to the body:

<div id="nav" class="jshidden"><a href="#"><p>Toggle</p></a></div>

The secret is a snippet of JavaScript in the header of the page to set a js class on body if JavaScript is enabled:

e.g.

<script>document.body.className+=' js';</script>

and then styling to hide any jshidden items

css:

body.js jshidden{
    display: none;
}

Your toggle code will override the styling, with inline styles, so will work as-is:

$(document).ready(function(){
  $("#nav").click(function(){
    $("#items").toggle();
  });
});

The advantage to all this is that the site will display the content if JS is not enabled (not a huge priority nowadays, but you never know when you might need this) :)

Upvotes: 0

DevAB
DevAB

Reputation: 373

first make the content to display none using css and then You can use jquery fadeToggle or slideToggle functions

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>

$(document).ready(function(){
  $("#nav").click(function(){
    $("#items").fadeToggle();
  });
});
</script>
</head>
<body>

<div id="nav"><a href="#"><p>Toggle</p></a></div>
<div id="items" style="display:none"><p >Content</p></div>
</html>

Upvotes: 1

Related Questions