Here is the content that you want to toggle:
<div id="stuff">
...
</div>
With the scripting, the best place to put your script (whether external or inline) is at the end of the body, just before the </body tag>
<html>
<head>
...
</head>
<body>
...
<script src="script.js"></script>
</body>
</html>
When someone loads your page and they don’t have any scripting, you don’t want the stuff to be automatically hidden because they then have no way to see it. That’s why we use scripting to hide the stuff, because scripting is also used to display it.
We also use a CSS declaration to hide it.
.hidden {
display: none;
}
Here’s how:
// hide stuff
var div = document.getElementById('stuff');
div.className = 'hidden';
You should not have a toggle link automatically shown on the page, because when people without scripting visit the page, the link will fail to work for them. Instead, use scripting to add the link. In this case, it’s added just before the stuff to be toggled.
// create link
var link = document.createElement('a');
link.href = '#' + div.id;
link.onclick = function () {
toggle();
}
// add link before stuff
div.parentNode.insertBefore(link, div);
That will create a link that looks like: <a href=“#stuff”>Toggle</a>
The link also directly calls the toggle function. That toggle function can now easily do its job by toggling the id that’s in the href reference.
We just need to deal with some browser compatability issues. Some browsers automatically add the page link on to the link when you retrieve it, so if we split at the # we can take whatever is after it.
function toggle() {
var id = this.href.split('#')[1];
var el = document.getElementById(id);
el.className = (el.className === 'hidden') ? '' : 'hidden';
return false;
}
Why do we return false? So that the web browser ignores what it normally does when links are clicked.
So the full script consists of three basic parts:
[list=1][]Hide the stuff
[]Create a toggle link
[*]Toggle the stuff[/list]
// hide stuff
var div = document.getElementById('stuff');
div.className = 'hidden';
// create link
var link = document.createElement('a');
var text = document.createTextNode('Toggle');
link.href = '#' + div.id;
link.appendChild(text);
link.onclick = toggle;
// add link before stuff
div.parentNode.insertBefore(link, div);
function toggle() {
var id = this.href.split('#')[1];
var el = document.getElementById(id);
el.className = (el.className === 'hidden') ? '' : 'hidden';
return false;
}
And best of all, it still works properly when scripting is disabled, because the content still remains fully accessible.