android.nick
android.nick

Reputation: 11207

Jquery: Why create a variable for something you're only referencing once?

So for something like this:

Jquery:

$(document).ready(function(){
    var container = $('.rotate_container');
    var images = container.find('img');
    container.everyTime(10, function (){
        images.each(function() {
            container.animate({scrollTop: $(this).offset().top - 165}, 2000).delay(1000);
        });
    });
});

What's the point of making the variables "container" and "images"? If they're each only used once, how does that help anything at all?

thanks.

Upvotes: 1

Views: 107

Answers (3)

jAndy
jAndy

Reputation: 236022

If you, for sure, only access an element once in your code, it does not make sense to cache it of course.

The reason for caching DOM elements is that it's awful expensive to access them.

Crossing the bridge between ECMAland and DOMland is the most expensive part. You really can compare it with a bridge, each time you cross it you have to pay a toll. So it makes sense to keep the stuff in ECMAland for which you already payed a toll. Do not cross the bridge each time you need it.

And in this picture you'll notice that it does not matter, if you only cross the bridge once.

Upvotes: 5

cletus
cletus

Reputation: 625097

Those variables essentially fix the values for each timed occurrence. If you think about it, the images could change, markup could be modified, etc. This fixes the DOM element set for the subsequent code. Whether or not is appropriate depends on the application.

Upvotes: 0

Emyr
Emyr

Reputation: 2371

you could replace images.each with container.find('img').each, but container would then be referred to 3 times (.everytime, .find('img') and .animate).

Upvotes: 0

Related Questions