I am trying to better understand how variables are stored with JavaScript and jQuery.
Using the below code, a separate variable called default_value is created for each .default-value element. Is this correct? Can it only be accessed from within the anonymous function that created it? I’ve heard the term “namespace”, and does it apply? Please provide any additional details so I can better understand what is going on.
Next, if I wanted to apply this to an element with a given ID instead of a group of a given class, then using each() appears unnecessary. How should it be modified?
$('.default-value').each(function() {
var default_value = this.value;
$(this).focus(function() {
if(this.value == default_value) {
this.value = '';
}
});
$(this).blur(function() {
if($.trim(this.value) == '') {
this.value = default_value;
}
});
});
What you are talking about is scoping.
Basically when you are in a function and use the
varkeyword (which you should) the variable is only available in the current scope (in your case in the anonymous function).If you would have skipped the
varkeyword the variable would be available in theglobalscope.When you want to get an element with an id (which is ALWAYS unique) in the DOM you could simply do:
Another thing you could do is using Jquery’s
hoverwhich handles both the.focus()and the.blur():