3

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;
        }
    });
});
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
user1032531
  • 24,767
  • 68
  • 217
  • 387

4 Answers4

7

Using the below code, a separate variable called default_value is created for each .default-value element. Is this correct?

Yes. The function is invoked for each, and the variable is scoped (via var) to the function.

Can it only be accessed from within the anonymous function that created it?

Yes (noting that the function creates more anonymous functions and they are within the function passed to each so they can also access it).

I've heard the term "namespace", and does it apply?

No

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
3

What you are talking about is scoping.

Basically when you are in a function and use the var keyword (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 var keyword the variable would be available in the global scope.

When you want to get an element with an id (which is ALWAYS unique) in the DOM you could simply do:

$('#theid').focus(function() { });

Another thing you could do is using Jquery's hover which handles both the .focus() and the .blur():

$('#theid').hover(function() {
  // focus in your code
}, function() {
  // blur in your code
});
Community
  • 1
  • 1
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
  • So, with the hover() approach, where is var default_value = this.value; declared? – user1032531 Apr 30 '12 at 16:36
  • @user1032531 I wouldn't use a variable in the first place to save the default value, but rather a [`data` attribute](http://api.jquery.com/jQuery.data/): http://jsfiddle.net/PeeHaa/ynnzY/ – PeeHaa Apr 30 '12 at 16:42
2

If you prefix a variable with var in javascript, it will contain it within the scope it was called, so in your case, var defaulf_value won't be accessible outside of the each loop you've created.

Without the var declaration, it will be global on the page.

You can namespace variables in JavaScript with JSON style objects.

When I'm writing javascript, I'll tend to define a namespace like this:

mynamespace = {};

Then, when you want to make a variable within that namespace you can call:

mynamespace.variableA = "Hello there";

That's a handy mechanism if you don't want to overwrite already pre-existing variables on the page. So for instance:

variableA = "First hello there";
mynamespace.variableA = "Second hello there";

console.log(variableA);
console.log(mynamespace.variableA);

Will print out:

"First hello there"
"Second hello there";

Even though you've used the same variable name, extending the second one won't override the first one because it's in a different namespace =)

Tom Dickinson
  • 382
  • 1
  • 8
1

a separate variable called default_value is created for each .default-value element. Is this correct?

Yes you are right. The default_value is created for each jQuery node found in the document. Every time you define a function you create an object that can contain private variables.

Can it only be accessed from within the anonymous function that created it?

Yes, but it is also accessible from function created inside that anonymous function.

I've heard the term "namespace", and does it apply?

The term namespace indicates a container of functions and variables. If you create a new JS library, is very important to avoid a conflict with others library. So instead of creating a global "load" function you create a namespace that will contain that function:

var myLibraryUniqueName = {};
myLibraryUniqueName.load = function() {};

Of course if the library is complex you can create inner namespaces:

myLibraryUniqueName.loginModule = {};
myLibraryUniqueName.animationModule = {};
...

Next you asked:

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

function defaultValue(node) {
  var default_value = node.value;
  node.focus(function() {
      if(node.value == default_value) {
          node.value = '';
      }
  });
  node.blur(function() {
      if($.trim(node.value) == '') {
          node.value = default_value;
      }
  }
}
defaultValue($('#id'));
mcmorry
  • 132
  • 1
  • 7