I started with this simple code with the aim of calculating the selector once.
(function($) {
var $mydiv = $('.mydiv');
var myFunc = function(){
$mydiv.css('background', 'red');
}
$(document).ready(function(){
myFunc();
});
$(document).resize(function(){
myFunc();
});
})(jQuery);
But I'm only able to get it to work by moving the selector inside of the doc ready but I dont understand why I need to do this.
(function($) {
var $mydiv;
var myFunc = function(){
if(!$mydiv){
$mydiv = $('.mydiv');
}
$mydiv.css('background', 'red');
}
$(document).ready(function(){
myFunc();
});
$(document).resize(function(){
myFunc();
});
})(jQuery);