Helping you solve those tough coding problems!

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

Published on Sep 26, 2012 by Jamie Munro

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

Tags: jquery | visible | hidden | toggle | jQuery

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP