Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to put all your code inside `$(document).ready`?

I'm using jQuery for a small project I have and it's one of my first times using it. Is it safe to put all my UI code in $(document).ready() ? I'm basically creating a form that pops up when a button is pressed, and the form is processed via AJAX. Basically, when I separate my AJAX function from the functions controlling the UI, the AJAX doesn't work. However, when I put both of them in $(document).ready(), everything works fine. Here's my code. Please ignore my comments, as they were for learning purposes.

$(document).ready(function(){ //ready for DOM manipulation

/*FORM UI*/
var container_form=$('#container_form'); //container form box
var addButton=$('.addButton'); //"+" add button
container_form.hide(); //initially hides form
$(addButton).click(function(){
$(container_form).toggle('fast');

/*SUBMISSION AJAX*/
$('form.ajax').on('submit',function() { //Make form with class "ajax" a JQuery object

    var that = $(this),                 //"that"-current form, "url"-php file, "type"-post, "data"-empty object for now
        url=that.attr('action'),
        type=that.attr('method'),
        data={};

    that.find('[name]').each(function(index,value){ //search all elements in the form with the attribute "name"
        var that=$(this), //legal attribute
            name=that.attr('name'); //name of the legal attribute
            value=that.val(); //value of text field in legal attribute
            data[name]=value; //data object is filled with text inputs
    });


    $.ajax({
        url: url,   //url of form
        type: type, //type of form
        data: data, //data object generated in previous
        success: function(response){ //reponse handler for php
            if(!response){
                console.log("Error");
            }
            console.log(response);
        }

    });


    return false; //Stops submission from going to external php page. 
});
});
});
like image 871
Carpetfizz Avatar asked Dec 04 '22 09:12

Carpetfizz


2 Answers

Generally any selectors such as $('form.ajax')., $('#container_form'), $('.addButton') needs to be in doc.ready to ensure that the DOM is ready before you try to select an element from it, since it may not find the element if the DOM hasn't finished processing. So that pretty much applies to all of your code. If you had a function such as this:

//defines a function
function addThem(first,second)
{
   return first + second;
}

You could declare it outside of doc ready, and call it from within doc ready.

$(document).ready(function(){
   $('#someInput').val( 
      addThem( $('#anotherInput').val() , $('#thirdInput').val()  )
   );
});

The way I think about this, is doc ready is an event, so you should be doing things in response to the "document is now ready for your to query event", not declaring things. Declaring function just says what that function does, but doesn't actually do anything, so it can go outside of the document ready. It'd be pretty silly to declare this function inside of doc.ready since it can be defined at anytime (although it certainly is possible to put it inside doc ready, it just generally clutters things up). Even if it were selecting an element, that code isn't actually running until it is called:

function hideContainer()
{
   //this code never runs until the function is called
   //we're just defining a function that says what will happen when it is called
   return $('#container').hide();
}

$(document).ready(function(){       
    //here we are calling the function after the doc.ready, so the selector should run fine
    hideContainer();
});

Note that the act of wiring up to other events is an action in itself, such as when you subscribed to the click events and form submit events. You are saying, "find the form element with class .ajax, and subscribe to its submit event". You wouldn't want to try and wire up to events of DOM elements until the DOM is done processing. They might not "exist" yet as far as the browser is concerned if it is in the middle of processing the DOM, and thus your attempt to wire up to the click/form submit events may fail. I say may because depending on timing/processing lag it may sometimes work and sometimes not.

like image 160
AaronLS Avatar answered Dec 06 '22 21:12

AaronLS


There's not only nothing wrong with putting all your code into one $(document).ready(), but there's nothing wrong with putting it into multiple $(document).ready() functions either so that you can separate repeated functionality into individual JS files.

For example, I use $(document).ready() in a script included on all my site's webpages to set up UI elements, prevent clickjacking, etc. At the same time, each page regularly has its own $(document).ready() which sets up page specific user interactions.

like image 45
sushain97 Avatar answered Dec 06 '22 23:12

sushain97