wayfarer
wayfarer

Reputation: 790

reducing repeated uses of jquery selectors

I'm learning jquery and I'm finding that I'm writing things like this all the time:

if ($("#Menu").zIndex()<200) {
    $("#Menu").zIndex(250)
    return;
}
else
{
    $("#Menu").zIndex(100)
    return;
}

I'm thinking that there must be a way to not have to repeat the $("#Menu")-type selector so much. I see that I could assign $("#Menu") to a variable, and then use that, but blows off the nice ".zIndex" method. Or I could do something with a function.

What are the best practices for this type of situation?

Upvotes: 2

Views: 84

Answers (2)

Hardy
Hardy

Reputation: 5631

Readability is good practice. You can also do inline statements like:

// Read this like "if zIndex is smaller than 200 new_z 
// value comes to 250 else 100"
var new_z = $("#Menu").zIndex() < 200 ? 250 : 100; 

$("#Menu").zIndex(new_z);

EDIT: avoid using string type reference to element more than once. Check @Nicholas Hazel answer.

Upvotes: 1

Nicholas Hazel
Nicholas Hazel

Reputation: 3740

A good indicator that you will be using a jQuery element, or something in the DOM, is to preface your variable with a $. That way, you know you're manipulating some HTML element rather than some standard var that is only needed for javascript to run.

So, you can use anything you'd like for your var name. I just decided to use $m to show how much easier it is to write than $menu or $("#menu")

Edit: Another benefit to caching it in a variable is your jQuery doesn't have to scrub your entire document every time you call it. Thanks for the callout @AdamMerrifield

So, something like this is typical practice.

var $m = $('#menu');

if($m.zIndex() < 200) {
    $m.zIndex(250);
    return;
} else {
    $m.zIndex(100);
    return;
}

Furthermore, you could certainly even shorten the code more with a ternary operator.

Learn More With Interactive Lesson

Copied From @Hardy's Response:

var $m = $('#menu');
var new_z = $m.zIndex() < 200 ? 250 : 100; 
$m.zIndex(new_z);

Upvotes: 5

Related Questions