Determine if an element is visible with Jquery Determine if an element is visible with Jquery

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.


function toggle(elementIdValue) {
}

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:


function toggle(elementIdValue) {
$(elementIdValue).toggle()
}

  1. 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

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.