Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up an init function in jQuery

Tags:

jquery

Just a quick question here, I wanted to find out how I could set up these into an init() function then have the function run on document.ready. This code is being used in a separate main.js file. Does it need to be called from the index page?

$('#main_right_line_one').click(function(){
    $('#main_regular_layover, #main_deep_layover').fadeOut('slow', function(){
        $('#main_light_layover').fadeIn('slow');
    });
});

$('#main_right_line_two').click(function(){    
    $('#main_light_layover, #main_deep_layover').fadeOut('slow', function(){
        $('#main_regular_layover').fadeIn('slow');
    });
});

$('#main_right_line_three').click(function(){
    $('#main_light_layover, #main_regular_layover').fadeOut('slow', function(){
        $('#main_deep_layover').fadeIn('slow');
    });
});

Any help is appreciated. I'm really trying to wrap my head around this, but I can't seem to find any good tutorials that explain init() well enough for my specific code.

like image 946
user2635811 Avatar asked Jul 30 '13 21:07

user2635811


1 Answers

No need for special "calls", include it on the page with <script src="yourfile.js"></script> and just wrap your code as below to make sure that it is executed after the dom is ready (and the elements present).

$(function () {
   // your code goes here

});

$( a_function ) is short for $(document).ready( a_function ); more about ready handlers in the documentation.


The reason why $(document).ready(...)/$(...) is needed at all is that jquery selection like $('#main_right_line_one') only sees elements that are present at the execution time in the DOM tree. However, <script> tag contents are usually executed by browsers as soon as they're met; and <script> elements are usually located in <head>. Thus the scripts would often see an incomplete DOM tree. Now, thanks to the design of jQuery, even if $('#main_right_line_one') does not match any elements, there would still be no error; and the click handler would be bound to 0 elements.

This all can be avoided by wrapping that kind of code in $(function() { ... }), which ensures that whatever code is in it will be executed after the DOM has been fully initialized (or immediately if it already has been initialized).


The reason for why there is a shorthand like $(function() {}) for $(document).ready(function() {}) is that executing code only after the DOM tree has been finished is such a necessary pattern that almost every single page utilizing jQuery would be using.