Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use $ and when not to

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.

like image 463
KJai Avatar asked Nov 29 '22 06:11

KJai


2 Answers

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.

like image 84
CaffGeek Avatar answered Dec 08 '22 00:12

CaffGeek


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
like image 38
Peter Bailey Avatar answered Dec 07 '22 22:12

Peter Bailey