I have this show/hide code. When the page opens (or is refreshed) the hide shows first. How can I make this code to work where the show doesn’t display until the link is clicked on?
```
<p><a href="#" onclick="toggleContent(); return false;">Click to toggle content</a></p>
<div id="content">
<p>This is the content to show and hide.</p>
</div>
<script>
function toggleContent() {
var content = document.getElementById("content");
if (content.style.display === "none") {
content.style.display = "block"; // Show content
} else {
content.style.display = "none"; // Hide content
}
}
</script>
</body>
</html>
I should add that the solution above is just a “quick and dirty” solution to get the job done. A better approach is to get the script to initially add display: none. That way, the content isn’t hidden from users who aren’t using JS. (I know people poopoo the not-using-JS concept, but honestly, I turn off JS on hundreds of sites, as it’s mostly not useful and is just intrusive. So there will be people who don’t have access to your content if it’s hidden by default.)
@Paul_Wilkins and others: Aren’t the stats where about 98% of all users, use JS? And is it true that many sites won’t operate correctly if JS is turned off?
It’s probably worth caveating that on the idea that browsers have made Javascript part of their inbuilt structure and defaulted it to on; meaning it wasnt really an active choice by the user to “use” JS…
Those are bad sites, designed by people who missed the memo about progressive enhancement. I turn off JS on many sites (via a one-click browser add-on) because JS is used for a lot of intrusive cruft that just gets in the way of the content (newsletter popups etc.)
I would take stats on non-JS users with a grain of salt.
I also often have to turn JS off when I’m in Spain as the connection is so slow in our area that virtually no pages will load and nearly all time out before loaded. Not everyone has the benefit of a good connection.