In this tutorial i am going to explain how can we hide or unhide elements on a webpage using simple javascript function. Let me tell you this function is very basic and can be extended according to your requirement. There are certain readymade libraries/frameworks available like jquery,prototype. These make it simple to achieve this task and also give you an option to animate your element before you hide or show them. But everything depends upon your requirement. Because you need to include this library on your webpage, everytime you want to use the functions defined it. Well, Lets start with our HTML code followed by the toggleElement() function defined in javascript. See the working demo below.
<input type="button" value="Hide" onclick="toggleElement(this);" > <div id="post196"> <h3>Contact Form</h3> <input type="text" size="20" value="sample text 1" ><br/> <input type="button" value="Sample Button" /> </div> |
I have defined the contents inside the div with id=post196, you can change the div contents and keep the ones you want. The function is called when you click the button and then it toggles the post196 div. Now let us see the javascript function which performs this toggle functionality.
function toggleElement(btn) { x=document.getElementById("post196"); x.style.display=(x.style.display=="block")?"none":(x.style.display=="none")?"block":"none"; btn.value=(x.style.display=="block")?"Hide":"Unhide"; } |
Save the above to block of codes inside a html file and modify it the way you want to 🙂
For those who want to know why we used display property as none and not hidden, can check my anotherblog entry.
Cheers !!
Realin !