Fresheyeball
Fresheyeball

Reputation: 30025

jQuery persistent non-event bindings

 var $thingy = $('.thingy'),
     $window = $(window);

 $window.on('resize', function(){
       thingy.width($window.width()/12);
 });

Is it possible to add more .thingys to the page and have them resize without re-querying?

I am aware that the following will work:

 var $window = $(window);

 $window.on('resize', function(){
       $('.thingy').width($window.width()/12);
 });     

the problem is, I am not adding .thingys to the page very often, making the creation of new jQuery objects and rapid re-querying of the DOM seem like alot of overhead.

Is there a better way?

Upvotes: 0

Views: 239

Answers (2)

Bergi
Bergi

Reputation: 665485

You can simply reassign to the variable:

var $window = $(window),
    $thingy = $('.thingy');
$window.on('resize', function(){
    $thingy.width($window.width()/12);
});


// then sometime:
$thingy = $('.thingy');
// or:
$thingy = $thingy.add(elements)

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 817128

Whenever you add a new .thingy, update the selection with

$thingy = $('.thingy');

or

$thingy = $thingy.add(the_new_thingy)

Of course $thingy must be visible in both places.

Upvotes: 1

Related Questions