Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I cache jQuery selections?

I need to cache about 100 different selections for animating. The following is sample code. Is there a syntax problem in the second sample? If this isn't the way to cache selections, it's certainly the most popular on the interwebs. So, what am I missing?

note: p in the $.path.bezier(p) below is a correctly declared object passed to jQuery.path.bezier (awesome animation library, by the way)

This works

    $(document).ready(function() {
        animate1();
        animate2();
    })
    function animate1() {
        $('#image1').animate({ path: new $.path.bezier(p) }, 3000);
        setTimeout("animate1()", 3000);
    }
    function animate2() {
        $('#image2').animate({ path: new $.path.bezier(p) }, 3000);
        setTimeout("animate2()", 3000);
    }

This doesn't work

    var $one = $('#image1'); //problem with syntax here??
    var $two = $('#image2');
    $(document).ready(function() {
        animate1();
        animate2();
    })
    function animate1() {
        $one.animate({ path: new $.path.bezier(p) }, 3000);
        setTimeout("animate1()", 3000);
    }
    function animate2() {
        $two.animate({ path: new $.path.bezier(p) }, 3000);
        setTimeout("animate2()", 3000);
    }
like image 371
David Fox Avatar asked Apr 10 '26 20:04

David Fox


2 Answers

If the images are not loaded when you call them, jQuery will return an empty object. Move your assignment inside your document.ready function:

$(document).ready(function() {
    var $one = $('#image1');
    var $two = $('#image2');
    animate1();
    animate2();
});
// ... etc.

If you need to cache them for later use outside of your initialization script then add them to a storage object:

var my_storage_object = {};
$(document).ready(function() {
    var $one, $two;
    my_storage_object.$one = $one = $('#image1');
    my_storage_object.$two = $two = $('#image2');
    animate1();
    animate2();
});
// ... etc.

Then later on, outside of document.ready you can call:

my_storage_object.$one //still has a reference to the jQuery object.
like image 168
Sean Vieira Avatar answered Apr 13 '26 12:04

Sean Vieira


   var one = $('#image1');
   var two = $('#image2');
    $(document).ready(function() {
        animate1();
        animate2();
    })
    function animate1() {
        one.animate({ path: new $.path.bezier(p) }, 3000);
        setTimeout("animate1()", 3000);
    }
    function animate2() {
        two.animate({ path: new $.path.bezier(p) }, 3000);
        setTimeout("animate2()", 3000);
    }

fix

when you do:

   var one = $('#image1');

you're storing the jquery object returned by the selector in the var "one". So you don't need to use $ anymore.

like image 23
fmsf Avatar answered Apr 13 '26 10:04

fmsf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!