jQuery: Simple Optimization – save jQuery selections to variables

Save selections into variables:

each $() represent a query, so if you’re doing multiple actions on the same ID, save the initial $() query to a variable and then use the variable to do actions on it later.

For example:
$(‘#id1’).action1();
$(‘#id1’).action2();
$(‘#id1’).action3();

This equals 3 jQuerys; 3 $(‘#id1’)

Refactor to:
var $id1 = $(‘id1’)
$id1.action1();
$id2.action2();
$id3.action3();

Having a ‘$’ in front of the variable is a common indicator that the variable is storing a jQuery selection.

Advertisements
This entry was posted in jQuery. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s