Javascript hideshow function

Hi I've been trying to get a hideshow function and came across one that works fine. The only problem for me is I would like my div to be hidden and then to be displayed onclick rather then displayed then hidden. here is a sample code:



   <!DOCTYPE html>
<html>
<head>
<script>

function hideshow(which){
if (!document.getElementById)
return
if (which.style.display=="none")
which.style.display="block"
else
which.style.display="none"
}

</script>
<style>

#adiv {
width: 320px;
height: 320px;
background: green;
}

</style>
</head>

<body>

<a href= "javascript:hideshow(document.getElementById('adiv'));";>clickme!</a>

<div id="adiv"> </div>


Hope this has enough info :)



Answers

You can initially hide the div in two popular ways:



(1) Hide using CSS



Add display:none to the div to hide the div whether JS is enabled or not. You can use something like this:



<div id="adiv" style="display:none"> </div>


(2) Hide using JS



Hiding via JS is useful if you don't want the div hidden for users that don't have JS enabled. There are various ways to hide the div using automatically executing JS. Below is a simple way to do this.



<body onload="hideshow(document.getElementById('adiv'));">

<a href= "javascript:hideshow(document.getElementById('adiv'));";>clickme!</a>
<div id="adiv"> </div>


Answers

I would like my div to be hidden and then to be displayed onclick rather then displayed then hidden




Trying to understand what you mean above, I can't guess anything else that you're talking about the original state of the <div>.

At the same time, I can't imagine you don't know how to achieve it!



Anyway, if that is really the question, it's pretty simple: add display: none; to your #adivrule.



BTW, you should prefer standard-compliant style for coding, to improve readability, like this:



   function hideShow(which){
if (!document.getElementById) {
return;
}
if (which.style.display == "none") {
which.style.display = "block";
} else {
which.style.display = "none";
}
}


And finally, you might also enhance it, so:



   function hideShow(which){
if (document.getElementById) {
which.style.display = which.style.display == "none" ?
"block" : "none";
}
}