Question

I have code containing jQuery code, but not all of the jQuery code is located within the $(document).ready function...

Only the event-handler is located within the document.ready function (which comes at the very end of the code - see bottom of my question/post for entire code). This event handler sends an AJAX POST request to the server upon the click of a send button.

       $(document).ready(function(){
            $('button.send').on('click',function(){
                chatSend($('.draft').val());
                $('.draft').val('');
            });
        });

However, there's other jQuery code before that document.ready function is performed...

My question is, is it only necessary that the event-handler for this code be in the document.ready function? If so, why is that the case?

Below is the ENTIRE CODE...

        var last_update_time;

        var current_time;

        var user_name=document.URL.match(/username=(.*)/)[1];

        var ajaxGet={
            url:'https://api.parse.com/1/classes/chats',
            type:'GET',
            data:'order=-createdAt'
        };

        function chatDisplay(object){
            object.filter(function(item){
                prependListItem(item);
            });
            last_update_time=object[0].createdAt;
        }

        function chatFetch(callback){
            $.ajax(ajaxGet).done(function(serverData){
                var serverString=serverData.results;
                callback(serverString);
            });
        }

        function chatSend(sendString){
            var chatString=user_name+": "+sendString;
            $.ajax({
                url:'https://api.parse.com/1/classes/chats',
                type:'POST',
                data:JSON.stringify({
                    text:chatString,
                    username:user_name
                })
            });
        }

        function refreshChat(passed_obj){
            $('.messages li:first').remove();
            appendListItem(passed_obj);
            last_update_time=current_time;
        }

        function refreshMsg(object){
            current_time=object[0].createdAt;
            if(current_time!=last_update_time){
                refreshChat(object[0]);
            };
        }

        function user_li_style(obj){
            var dynamicClass;
            var txtUser=obj.text.match(/[^:]*/i)[0];
            if (txtUser==user_name){
                dynamicClass="myTxt";
            } else {
                dynamicClass="otherTxt";
            }
            return dynamicClass;
        }

        function appendListItem(obj){
            $('.messages').append('<li><div class="'+user_li_style(obj)+'">'+chatTextFilter(obj)+' ('+obj.createdAt+')</div></li>');
        }

        function prependListItem(obj){
            $('.messages').prepend('<li><div class="'+user_li_style(obj)+'">'+chatTextFilter(obj)+' ('+obj.createdAt+')</div></li>');
        }

        function chatTextFilter(obj){
            var smile="<img src='img/smile.png' alt=':)'>";
            var myRegEx=/:\)/g;
            return userIdentify(obj).replace(myRegEx,smile);
        }

        function userIdentify(displayText){
            var replace_text="<span class='myName'>"+user_name+"</span>";
            return displayText.text.replace(user_name,replace_text);
        }

        chatFetch(chatDisplay);

        setInterval(function(){
            chatFetch(refreshMsg)},2000);

        $(document).ready(function(){
            $('button.send').on('click',function(){
                chatSend($('.draft').val());
                $('.draft').val('');
            });
        });

Also, and this is unrelated, but why does the event-handler in this code not need a preventDefault() call, whereas the code in the following link (this is a link to code that creates a similar chat application) utilizes the preventDefault() in the relevant event handler...

        bindSendEvent: function () {
        $(".send").on("click", function (e) {
          var input = $(".draft");
          myChat.send(Chat.username + ": " + input.val());
          input.val("");
          e.preventDefault();
        });
      },

link for entire code to app B (from which the above bindSendEvent function is found)

Was it helpful?

Solution

Read what $(document).ready() does: http://api.jquery.com/ready

If the code interacts with the dom, and would otherwise be executed before the element exists, you can move the code to inside of the dom ready handler so that the code won't run until after the element exists.

Sadly, it is very common for much more code to be included inside the document ready handler than is really needed, resulting in code that executes slightly later than it could have otherwise.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top