views:

254

answers:

4

I have selected a control using the following variable

var txt = $("#text1");

Now when I have to handle events on the textbox, do I have to reference it as $(txt) or txt will do

$(txt).keydown(function() {})

or

txt.keydown(function(){})

What is the advantage. Please explain it taking the variable txt as the context.

+17  A: 

If txt is already equal to a jquery object, there is no need to use $(txt) as it's just extra processing to return the same thing.

Chad
+5  A: 

The best approach is to declare your variables so know what they are. Basically, what I'm saying is apply some apps hungarian and prefix your jQuery variables with a $

var $text1 = $("#text1");  // this is a jQuery object
var text1 = $text1[0];     // this is not
Peter Bailey
i've also found this to be a good practice!
Sander Versluys
If a framework requires that you have to evolve practices like these, it's deeply disturbing.
Rakesh Pai
@Rakesh - first of all, nobody is insinuating that it's *required*. Secondly, I suspect you've never worked with large amounts of jQuery otherwise you'd know how intensely useful this simple convention is. Remember, Apps Hungarian is the *good* type of Hungarian Notation.
Peter Bailey
A: 

A bit more info on Chad's response.

The $() is a short cut to the commonly used function document.getElementById().

Once you lookup and store the object's value you don't need to look it up again. As Chad mentioned. Ask your self is the variable an object or a name (string), if it's a name you will have to lookup the object.

Joel
You are incorrect. From the OP's example code, it's clear that he's using jQuery, in which case `$(…)` is jQuery's "dollar function": http://docs.jquery.com/Core/jQuery
Ben Blank
Ben good eye. I was thinking of the prototype $() function.
Joel
A: 

In my experience I've found that using $(txt) yields more predictable results compared to assigning it as a reference ans using the reference to call the same methods/properties. It's possibly superstition on my part, however a few of us at work have been foiled by using a reference such as txt rather than an implicit $(txt) once txt has been assigned.

Antony Koch