javascript - jQuery unable to find element unless inside doc ready -


this question has answer here:

i started simple code aim of calculating 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 able work moving selector inside of doc ready dont understand why need this.

(function($) {      var $mydiv;     var myfunc = function(){          if(!$mydiv){              $mydiv = $('.mydiv');          }          $mydiv.css('background', 'red');     }      $(document).ready(function(){         myfunc();     });      $(document).resize(function(){         myfunc();     });  })(jquery); 

why document ready necessary?

because html takes time render while javascript start executing load, document ready make sure html loaded before start accessing via jquery or javascript.

otherwise $('.elementclass') return null dom not loaded script go unexpected.

as stated here:

a page can't manipulated safely until document "ready." jquery detects state of readiness you. code included inside $( document ).ready() run once page document object model (dom) ready javascript code execute. code included inside $( window ).load(function() { ... }) run once entire page (images or iframes), not dom, ready.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -