JavaScript is a client side scripting language that runs in browser. Often you would have seen animations on your websites even If they are disconnected from the server. The reason is that all the JavaScript code is sent to the browser by the server and browser is responsible for interpreting and displaying corresponding animations. In this article we are going to see how we can make a simple expand/collapse menu using JavaScript. Let’s jump straight to the code followed with its explanation.
<!HTML>
<head>
<title> JavaScript Expand/Collapse Example </title>
</head>
<body>
<div id=”DivElement” style=”display: block; border-radius:50px; padding-left:40px; width:200px; height:200px; background-color:red;”>
<h1>Welcome to Bytescout</h1>
</div>
<a id=”ToggleButton” style=”display:block; text-decoration:none; width:100px; height:25px; background-color:yellow”
href=”javascript:showhide();”>Hide Element</a>
<script language=”javascript”>
function showhide() {
var divele = document.getElementById(“DivElement”);
var togbutton = document.getElementById(“ToggleButton”);
if(divele.style.display == “block”) {
divele.style.display = “none”;
togbutton .innerHTML = “Show Element”;
}
else {
divele.style.display = “block”;
togbutton .innerHTML = “Hide Element”;
}
}
</script>
</body>
</HTML>
This is a simple HTML code. You can copy and paste the above code in a text file and then save it in .html or .htm format. The webpage contains one div element with Id “DivElement” and one link with id “ToggleButton”.
By default the display type of DivElement is a block and its width and height both are of 200 pixels. By default the link contains the text Hide Element. When the link is clicked, JavaScript function “showhide” is executed. Inside the function the display type of the “DivElement” is checked. If it is block, the JavaScript code changes it to none which makes it disappear. The text of the link is changed to “Show Element”.
Next when this link is clicked, again “showhide” function is called and this time the display type of the DivElement will be none, so the code in the else section of the showhide function will be executed and the display type of the element will be changed again to block which will make DivElement appear again on the page. The text of the link will be changed to “Hide Element again”. Consider following screen shots for the output of the above code.
-
Before Hide Button is clicked
-
After the Hide Element Link is clicked