- The extremely simple Jquery solution:
function toggle(elementIdValue) {
$(elementIdValue).toggle()
}
- The good old fashion none JavaScript route:
function toggle(elementIdValue) {
if (document.getElementById(elementIdValue).style.display == "none")
document.getElementById(elementIdValue).style.display = "block";
else
document.getElementById(elementIdValue).style.display = "none";
}
Both work to accomplish the task at hand; however, I don't like the idea of using toggle or the old school JavaScript route when I want to know if the element is visibile. Jquery offers one other nice solution. Let's rewrite example two above to use it:
function toggle(elementIdValue) {
if ($(elementIdValue).is(":visible"))
$(elementIdValue).hide();
else
$(elementIdValue).show();
}
Or rather than using visible you could use the opposite – hidden – to detect if it is not visible.
Image courtesy of Sweetie187
Published on Sep 26, 2012
Tags: visible
| hidden
| toggle
| jQuery Tutorial