If variable = number, do X, else do nothing

dylfreak6494 picture dylfreak6494 · Jan 21, 2012 · Viewed 41.7k times · Source

I wrote a jquery code that is going to expand certain elements on hover. I want the code to only expand if not expanded. Here is my code. It doesn't seem to be working correctly.

$(document).ready(function() {
    var labelstatus = 0;
});
$(document).ready(function() {
    $("a.rm").hover(function () {
        if (labelstatus != 1){
            $("#expensereduction,#envimpact,#mtextlft,#initaud,#energaud").fadeOut();
            var currentFontSize = $('.initiate').css('font-size');
            var currentFontSizeNum = parseFloat(currentFontSize, 10);
            var newFontSize = currentFontSizeNum*3;
            $('.initiate').delay(500).animate({
                fontSize: newFontSize
            });
            return false;
            var labelstatus = 1;
        }
        else {
        }
    });
});

Answer

user1106925 picture user1106925 · Jan 21, 2012

this...

    return false;
    var labelstatus = 1;

should be...

    labelstatus = 1;
    return false;

...and this...

$(document).ready(function() {
    var labelstatus = 0;
});

should be...

var labelstatus = 0;

  • Code that comes after the return statement will not run

  • Using var makes labelstatus local to the function

  • You really don't need two $(document).ready(function() { calls. Put your code in one, and you can make labelstatus local to that handler so that all code inside can use it.