I have a bit of an issue with a toggle visibility function which operates on the hidden attribute of an element. Trouble is, this lacks browser compatibility..
function hide(e) {$(e).hidden=true;}
function show(e) {$(e).hidden=false;}
Googling this issue I came across the method of toggling the style.display property, like so..
function toggle(e) {
document.getElementById(e).style.display = (document.getElementById(e).style.display == "none") ? "block" : "none";
}
..but this seems sub-optimal, because you can’t have a generic show/hide function that sets the display property to block. What if the element in question sometimes is supposed to have a inline or something?
How does for example jQuery solve this issue?
It stores the old
displayvalue in adataattribute calledolddisplayand then uses the value of that to restore it when showing the element again. See the implementation here. You can check the implementation of any jQuery method on that site.In the following code snippets I’ve annotated the important line with a
//LOOK HEREcomment.The important part of the
showmethod:When hiding an element it firstly stores the current
displayvalue in adataattribute:And then simply sets the
displayproperty tonone. The important part:Note
The above code is taken from jQuery version 1.6.2 and is obviously subject to change in later versions.