Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a variable exists in jQuery?

Is there a way to create a variable in jQuery / JavaScript if it not exists?

I've tried:

    if (moving.length<0) {
        moving=false;
    }

    if (moving=='undefined') {
        moving=false;
    }

But logically it all failes because the initial check on the variable is already undefined.

Hope you guys can help :)


EDIT

First answer worked properly but my problems with this continue.

$.fn.animation = function() {
    if (typeof moving == 'undefined') {var moving = false;};

    if(moving===false){
        var moving=true;
        console.log('test');
    };      
};


$(window).scroll(function(){
    if($(window).scrollTop() < scrollpos){
        elm.animation();
    }
    scrollpos=$(window).scrollTop();
});

In this setup 'test' gets constantly logged even if I log moving which is set to true the if still gets ignored.

So what I want to archive is that every time I scroll the element get checked if its already animated. If so, don't do the animation.

Basically a queue.

like image 596
ceed Avatar asked Jan 10 '14 22:01

ceed


2 Answers

Did you try

if (typeof moving == 'undefined') var moving = false;

In some cases I use

var moving = typeof moving == 'undefined' ? false : moving;

which is basically the same, but for me it's more readable in some cases to see that the variable is set, either to it's original value, or false if it's undeclared, but the first version is more common.

EDIT:

Here's how to detect scroll

var scrolled = false;

$(window).on('scroll', function() {
    scrolled = true;
});

//later

if (scrolled) {
    // do stuff
}
like image 173
adeneo Avatar answered Nov 14 '22 02:11

adeneo


if( typeof moving === 'undefined' )
{
    var moving;

    moving = false;
}

Will work.

like image 21
deW1 Avatar answered Nov 14 '22 00:11

deW1