Not feeling too well, hope I don't get sick tomorrow. :(

3 days, 3 hours ago

Rss

Attack of the ‘if statements’

The small project I’m working on requires a lot of front end visual effects, so this means a lot of JavaScript coding! The one thing I love about coding in JavaScript is just how pure simplicity can turn into one confusing function. Let’s have a look at an extract from the JS file:

function goHome(){
     $im1 = $("div.links").css("display");
     if($im1 == ‘block’){
          $("div.links").hide("slow");
     }

     $im2 = $("div.contact").css("display");
     if($im2 == ‘block’){
          $("div.contact").hide("slow");
     }
     $dpL = $("div.front").css("display");
     if($dpL == ‘none’){
          $("div.front").show("slow");
     }
}

So, why 3 ‘if statements’? Well, because the content appears in the same DIV tag, I need to hide or show whatever the user requests without having the other content being in the way. To prevent this, I check the current CSS Display value to see whether or not I need to hide or show it. In it’s simple form, “if it’s hidden, show it”, but above is what it actually is.

The JS for the project is powered by jQuery.

(3) comments

John Resig said:

Actually, in jQuery 1.1.3 you no longer have to do the if statement - a ’show’ animation isn’t done if the element is already visible (and a ‘hide’ animation isn’t done if an element is already hidden).

Also, another way that you could’ve written your code:

function goHome(){
$("div.links:visible").hide("slow");
$("div.contact:visible").hide("slow");
$("div.front:hidden").show("slow");
}

John Resig said:

Apparently code blocks get munged, trying something different:

function goHome(){
$(”div.links:visible”).hide(”slow”);
$(”div.contact:visible”).hide(”slow”);
$(”div.front:hidden”).show(”slow”);
}

Jarques said:

Oh, thank you. I’m still getting used to jQuery. I’ve been an extensive user of Scriptaculous.

Leave a Reply

Avatars are powered by Gravatar.com