Determine if an element is visible with Jquery

D

When I interview web developers, I always like to ask the following basic Javascript question:

Write a function in Javascript that will ‘toggle’ or show/hide an element upon being fired.
[code]
function toggle(elementIdValue) {

}
[/code]

I typically see one of two answers: Jquery or classic JavaScript.  Both of course are effective.  But, in this article I’m going to demonstrate another way as well.

  1. The extremely simple Jquery solution:

[code]
function toggle(elementIdValue) {

$(elementIdValue).toggle()

}
[/code]

  1. The good old fashion none JavaScript route:

[code]
function toggle(elementIdValue) {

if (document.getElementById(elementIdValue).style.display == “none”)
document.getElementById(elementIdValue).style.display = “block”;
else
document.getElementById(elementIdValue).style.display = “none”;

}
[/code]

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:

[code]
function toggle(elementIdValue) {

if ($(elementIdValue).is(“:visible”))
$(elementIdValue).hide();
else
$(elementIdValue).show();

}
[/code]

Or rather than using visible you could use the opposite – hidden – to detect if it is not visible.

Image courtesy of Sweetie187

About the author

By Jamie

My Books