How to toggle display of page elements with JavaScript
Posted: Mon Mar 01, 2010 1:29 am
This mini tutorial explains how to show/hide elements on a web page using JavaScript. There are many reasons why you would want to do this, and luckily it is very simple.
All it takes is changing the display CSS property. Setting display: block; (the default for div tags) makes it visible, and display: none; makes it hidden. The advantage to using display is that other items on the page will move to close the void left by the hidden object.
Fist, we'll start with creating the function:
We will call this function, passing the id of the targeted object. We now need to get a handle of the object identified.
Now that we have the object, we need to check what display is currently set to. We will then change it accordingly.
As you can tell, accessing CSS properties is done using object.style.property, replacing "property" with the desired property. Changing is as easy as changing a variable.
That's all there is to the JS function!
Now to use it, we just need to call the function with a link, button, or any event. For example:
When the user clicks the link, it will call the function. I also added return false; to the event to stop the browser from following the link (prevents the page scrolling up).
Here is the whole example page:
All it takes is changing the display CSS property. Setting display: block; (the default for div tags) makes it visible, and display: none; makes it hidden. The advantage to using display is that other items on the page will move to close the void left by the hidden object.
Fist, we'll start with creating the function:
Code: Select all
function toggleDisplay(id) {
}
Code: Select all
function toggleDisplay(id) {
var obj = document.getElementById(id);
}
Code: Select all
function toggleDisplay(id) {
var obj = document.getElementById(id);
if(obj.style.display == 'none') {
// show the object
} else {
// hide the object
}
}
Code: Select all
function toggleDisplay(id) {
var obj = document.getElementById(id);
if(obj.style.display == 'none') {
obj.style.display = 'block';
} else {
obj.style.display = 'none';
}
}
Now to use it, we just need to call the function with a link, button, or any event. For example:
Code: Select all
<div id="div">Test Object</div>
<a href="#" onClick="toggleDisplay('div'); return false;">Show/Hide</a>
Here is the whole example page:
Code: Select all
<html>
<head>
<title>Toggle Display</title>
<script type="application/javascript" language="javascript">
function toggleDisplay(id) {
var obj = document.getElementById(id);
if(obj.style.display == 'none') {
obj.style.display = 'block';
} else {
obj.style.display = 'none';
}
}
</script>
</head>
<body>
<div id="div">Test Object</div>
<a href="#" onClick="toggleDisplay('div'); return false;">Show/Hide</a>
</body>
</html>