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 :)
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.
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
}
if( typeof moving === 'undefined' )
{
var moving;
moving = false;
}
Will work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With