0

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);
John Magnolia
  • 15,835
  • 30
  • 147
  • 254

2 Answers2

2

why document ready is necessary?

because Html takes time to render while javascript start executing as it load, so document ready make sure html is completely loaded before you start accessing it via jQuery or javascript.

otherwise $('.elementClass') will return null as DOM is not loaded so all your Script will go unexpected.

As stated here:

A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).load(function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.

Zaheer Ahmed
  • 26,435
  • 11
  • 70
  • 105
1

My guess is that .mydiv does not exist in the body when the script is being run.

Your script tag in the HTML could be above the elements with the mydiv class.

Try moving your script tag to the bottom of the body.

logikal
  • 1,087
  • 12
  • 24