Registration for jQuery Conference 2008 is closed.

Introducing $(document).ready()

This is the first thing to learn about jQuery: If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.

JavaScript:
  1. $(document).ready(function() {
  2.     // put all your jQuery goodness in here.
  3. });

The $(document).ready() function has a ton of advantages over other ways of getting events to work. First of all, you don't have to put any "behavioral" markup in the HTML. You can separate all of your javascript/jQuery into a separate file where it's easier to maintain and where it can stay out of the way of the content. I never did like seeing all those "javascript:void()" messages in the status bar when I would hover over a link. That's what happens when you attach the event directly inside an <a href> tag.

On some pages that use traditional javascript, you'll see an "onload" attribute in the <body> tag. The problem with this is that it's limited to only one function. Oh yeah, and it adds "behavioral" markup to the content again. Jeremy Keith's excellent book, DOM Scripting, showed me how to create an addLoadEvent function to a separate javascript file that allows for multiple functions to be loaded inside it. But it requires a fair amount of code for something that should be rather straightforward. Also, it triggers those events when the window loads, which leads me to another advantage of $(document).ready().

With $(document).ready(), you can get your events to load or fire or whatever you want them to do before the window loads. Everything that you stick inside its brackets is ready to go at the earliest possible moment — as soon as the DOM is registered by the browser, which allows for some nice hiding and showing effects and other stuff immediately when the user first sees the page elements.

46 Responses to “Introducing $(document).ready()”

  1. Jörn Says:

    Even for this little amount of code is a shortcut available:

    $(function() {
    // do something on document ready
    });

    A function passed as an argument to the jQuery constructor is bound to the document ready event. Since the last update to the documentation its even documented :-)

  2. karl Says:

    Whoa! I had no idea. Thanks for the info!

  3. Michael Geary Says:

    There is no guarantee that the document has not already been rendered on the display at the time that $(document).ready() or $( function(){} ) fires. You *may* be able to show and hide display elements at this time without causing display flashing, but you can't count on it.

  4. karl Says:

    Michael, that's very interesting. Thanks for mentioning this! I must say that I haven't run into a problem with the display flashing except for one case and only with Safari (and it was particularly vexing because I hadn't expected it). Do you have any recommendations for a way to show/hide display elements that you can count on?

  5. Jörn Says:

    Hey Karl, looks like you added another comment instead of editing the first an :-)

    A scenario where you see content before the ready event is fired is when using incremental page loading. This could occur when displaying a big table. While you can see the first rows, the DOM is not fully loaded yet.
    Therefore its always a good idea to hide stuff via CSS if it is not intended to be visiable on page load.

  6. karl Says:

    Oops. You're right, Jörn. I just deleted the f irst draft, which was more terse and less sociable. Thanks for the great comments so far on this blog. With people like you contributing, it's sure to be a success.

  7. Chris Ovenden Says:

    Jörn said: "its always a good idea to hide stuff via CSS if it is not intended to be visiable on page load"

    This is an accessibility issue. IMO you should never hide content in the stylesheet that can only be revealed with javascript, since js may not be available; display:hidden declaratons should be scripted in some way so that the hide will fail precisely when the ability to show fails. I'm not sure how to avoid the flash of content though, without adding some js to the page itself.

  8. Rob Says:

    You could use window.onload :) Seriously, use document/ready for stuff that can be loaded in before images, but use window.onload for stuff to be done after the whole thing is loaded.

  9. Ranjan Says:

    i m totally new in jquery. i m woring in ASP.Net. i just know that jquery library is add with website. after that where use this function and in which tag.

    $(document).ready(function() {
    // put all your jQuery goodness in here.
    });

    plz give me reply. i want to learn jquery from starting. plz tell me website which also give examples

    thanks

  10. Karl Says:

    Hi Ranjan,

    Ideally, you would put that function in a separate file and then include a reference to it in your page's <head>. You could also put the code directly in the <head> between <script type="text/javascript"> and </script>.

  11. Rusu Dragos Says:

    Can .ready() event be used on other tags than document?

    For example I have a form that targets an iframe. I need to make some modifications to the output that comes in my iframe.

    Any way I could test if my iframe is empty or not?

  12. Karl Says:

    Rusu, I don't think jQuery has an $('element').ready() method, yet. It always assumes document. Have you tried $('element').load()? That might do the trick.

  13. Omar Says:

    Hi,

    I'm still new in jquery, i have used it only with jCarousel but i got a javascript error that 'jQuery is not defined', although i included the jquery.js in the head of my code...

    here is snippet of that function:

    jQuery(document).ready(function() {
    	jQuery('#mycarousel').jcarousel({
    		vertical: false,
    		start: 1,
    		size: 4,
    		itemWidth : 100,
    		itemHeight : 100,
    		itemVisible: 1,
    		itemScroll: 0,
    		nextButtonStateHandler: 'prev',
    		prevButtonStateHandler: 'next'
    	});
    });

    Thanks for all,

  14. Karl Says:

    Hi Omar, that error message almost always occurs when the reference to jquery.js is incorrect. If you could point me to a live page somewhere, I'd be happy to take a look, even though I'm not familiar with the jCarousel plugin.

  15. Omar Says:

    Thanks Karl, i forgot to tell you that i'm using jCarousel and jQuery in a project built using drupal and if you know drupal it offers 'modules' called jCarousel and jQuery and those modules are ready to use, you should only bind it with your project...

    if you know anything about this subject, please tell me. thanks again

    I'm sorry Karl, i can not give you a look, since there is nothing to have a look at:-)

  16. itsadok Says:

    Can .ready() event be used on other tags than document?

    I think the frameReady does what you're looking for.
    http://ideamill.synaptrixgroup.com/?p=6

  17. Karl Says:

    I'm sorry, Omar, but I don't know enough about that subject to help without seeing what's going on. You'll have much better luck posting a question to the jQuery Discussion List (Google Group).

  18. Darren Oh Says:

    I see this error on occasion and can provide some details. Drupal includes jQuery 1.0.4. The error occurs on jquery.js line 1923. No idea why. jQuery is obviously defined at that point.

  19. Karl Says:

    Hi Darren,

    Again, this is the sort of thing that will get much more attention on the jQuery Discussion List.

  20. Kevin Says:

    I'm just begin to use JQuery, Thanks for the info!

  21. Fred Says:

    Hi!
    I try use the code $(document).ready() ... but i receive the follow error: $(document).ready() s not a function.

    And i include in my page html the librarys jquery-lalest.js, jquery.tablesorter.js and jquery-1.2.1.js.

    Some bory know whats happened?

  22. Karl Says:

    Hi Fred,
    You shouldn't need both jquery-latest.js and jquery-1.2.1.js. One or the other is fine. Do you have a publicly available page that I can have a look at? It would make it easier for me to help you troubleshoot the problem. Usually, though, with that sort of error, the problem is that you're pointing to the wrong location for your jquery.whatever.js file

  23. Ryan Says:

    What is the difference between $document.ready() and jQuery().ready()? I've seen examples using each.

  24. sunil Says:

    hi Ryan,
    $(document).ready() and jQuery(document).ready() are both the same. And to query some Link click we should use $("a").click()

  25. Nick Fletcher Says:

    I know this is quite old, but:

    Rusu, I don't think jQuery has an $('element').ready() method, yet. It always assumes document. Have you tried $('element').load()? That might do the trick.

    I'm not sure how it would be possible to use $('element').load()

    You would need to bind the event at some point prior to the element "loading". You can't do it in $(document).ready() because the element is obviously already loaded and thus you would never receive the event. And you can't do it outside of a window load even within the <head> because the element wouldn't exist yet.

    The best solution that I can think of would be to add an inline <script> tag right after the element in the page. It executes immediately after the element is loaded and you're guaranteed that it exists. Of course this solution is quite obtrusive and goes against many best practice guidelines.

    I think your best bet is to avoid trying to do this all together. :P

  26. PAStheLoD Says:

    Hello!

    I've encountered a rather interesting problem. I've an object constructor (some might even call it a class), and in a public function (method) I try to use $(document).ready();

    Here's the source:

    this.inject = function(id){ $(document).ready( function(){ _inject(id); } ); };

    My problem is, that when jQuery pushes this anonymous function onto its list, and then executes it later, the context is not my object, but the window. And somehow the _inject(id) executes (although being a "private" function) in that context, and then it's getting messier, when I try to use

    gNextButton.addEventListener("click", this, false);

    And the this references the windows instead of my object. And this makes me cry. :C

    Halp plz ^.^

  27. Karl Says:

    I recommend that you bring this up to either the jQuery discussion group or the jQuery Dev group.

  28. PAStheLoD Says:

    Thanks for the tip, I shall try there then :)

  29. Ing Angel Lacret Says:

    hi, I´m from Venezuela and this is my problem

    I´m programming an aplication with jquery Ajax functions, i work all the stuff in only one page, I use a function that loads in a main DIV the page that i call acording to the selection on a menu, the pages that are been loaded do the same, they have function that render pages inside their internal DIVS and also use the $(document).ready(function), the thing is when i render an internal page DIV with the internal reference to the function, because when i do that and then i want to call another page fron the main menu, the $(document).ready( function) stop working on the INTERNALS.

    I've try many things an the problem persist, it only disappear when i reload the page....

  30. Karl Says:

    Ing Angel Lacret: I'm not sure if I'm understanding your question correctly, but I think this FAQ item should help.

  31. Daedal Says:

    Hello!

    I am really newbie when it comes to jQuery, still learning thought but for now i will have to bother you :). Ok here is my problem, Ajax related and i really tried reading those solutions posted above and in FAQ but without results :(.

    I am working on one site that will have slide panel and i have to incorporate Ajax search as you type, those two separately work like a charm but together slide panel doesn't work and i get that usual error: "$(document).ready is not a function".

    Please help if you can, it would be much appreciated!

    This is copy/paste of slide panel function:

    jQuery ver: 1.2.3
    $Date: 2008-02-06 00:21:25 -0500 (Wed, 06 Feb 2008) $
    $Rev: 4663 $

    
     $(document).ready(function(){
    	$(".btn-slide").click(function(){
    		$("#panel").slideToggle("slow");
    		$(this).toggleClass("active"); return false;
    	});
    });
    

    ...and in here you can see Ajax js code that is in collision with jQuery:

    it is too big for posting it in here
    http://www.2bpx.com/suggest.js

    Thank you all in advance...

  32. Greg Says:

    Daedal,

    That means jquery isn't loading in your web page. Probably because you're pointing to the wrong place.

  33. Greg Says:

    Daedal,

    That probably means jquery isn't loading in your web page. Probably because you're pointing to the wrong place.
    Alternately, you may have a javascript typo that's messing with the library, such as a missing quote or semicolon, but I would check the first thing.

  34. Daedal Says:

    Thank you Greg for responding so promptly but unfortunately that is not a solution.

    I checked everything twice and the thing is as i said before panel and Ajax search are working correctly separate but together i get an error and panel doesn't work, search does. So as long i have jquery.js and suggest.js included on site together, panel doesn't work and as soon as i comment out suggest.js it works like a charm.

    Panel i need cause whole site control panel will be incorporated (site is small CMS sort to speak) there and ajax search cause of separate quick search from db, also very needed. I've read Karl's suggestion to read FAQ and "Why do my events stop working after an Ajax request?" but i can't get it to work :(

  35. Daedal Says:

    Ok sorry, really sorry!

    I found a solution, well it is a auto php generated site which has two html parts in it, one is served for logged users and one for not logged. I was modifying headers and i forgot to put jquery to logged-in version so it messed everything up :(

    Once again i apologize for my mistake and thank you for help. Now everything works like a charm!

  36. Matt Says:

    I am using about 5 slide panels on our new intranet site as part of the page navigation.

    We are currently on IE6 across the business.
    On some users machines the panels display their content on page load (i guess this is what you are calling "Display flashing" before rolling up to their hidden state.

    On other users machines this affect does not happen.
    How do i get around this?
    I was looking at the document ready function to see if this was the issue but what is really throwing me is that it functions correctly on some machines and not others, is this possibly a Java version issue?

    I also have another question, is it good practice to place the document ready function in a js file and call the file rather than actually placing it onto the page?

    Any feedback would be appreciated.

  37. Karl Swedberg Says:

    Hi Matt,

    There is an issue with document ready with jQuery versions 1.2.3 and 1.2.4. It now waits for CSS to load, but that might not always be desirable. You can find a discussion of it and a workaround on the jQuery Dev google group. It's possible that you're seeing the problem only on less powerful machines or ones with browsers that are being slowed down for some other reason.

    Yes, it is a good practice to put all your custom scripts in separate js files.

  38. Eirik S Says:

    what about functions that needs to be available also after page load, and after elements in the page is "tampered with"?

    I use jquery to send data (text) from one file to another. The second file stores the text to in database and the first file includes the second file, which now contains the fresh piece of text. The second file is included with load()

    $("#whereAllTheTextIsListedOut").load("secondFile.php .givNewStuffThisClass");

    But this content that isn't loaded "on window.onload" does not behave like the content that comes by a full page reload. All the functions I have to do stuff to this content (delete, edit,..) does not work until I reload the page.

    Is there any alternatives to this window.onload (or in jquery $(document).ready())?

  39. Karl Swedberg Says:

    Hi Eirik,

    In the jquery.com documentation site, there is an FAQ page that answers your question and provides links to a few plugins to help with your situation. Also, I recently wrote two tutorials on the topic: Working with Events, part 1 and Working with Events, part 2.

  40. Eirik S Says:

    sweet, thanks Karl that's just what I need.
    awesome!

  41. cybercow222 Says:

    can i ask one nob question, why the dollar sign prefix "$" before the constructor function names, it seems like php var declaration but`s not ... cheers ...

  42. Karl Swedberg Says:

    Hi there,

    The "$" is just an alias for the jQuery() method. So, the above code would work just as well written like this:

    jQuery(document).ready(function() {
    	// put all your jQuery goodness in here.
    });

    A lot of JavaScript libraries use the dollar symbol, but only because it's a single character. Nothing special about it.

  43. shan Says:

    Is am I able to pass argument to the function. Because i want to use id of the perticular control.

  44. Yavuz Bogazci Says:

    Hi,

    i am new to jquery and wanted to build a simple website to test it. in the <head> part of my page i have this javascript

    
    $(document).ready(function() {
    		$.ajax({
      		  type: "POST",
    	      url: "ajax.tasklist.php",
    	      dataType: "html",
    	      beforeSend: function(){$("div.loading").show()},
    	      complete: function(){$("div.loading").hide()},
    		  success: function(msg){
    		  	$('div#tasklist').html(msg);}
    		});
    	});
    
    	function save() {
    		alter ("hallo");
    	}
    

    in the html part the following elements

    
    
         
        urlfield
        save
        Link
    
    

    each time when i click on "save" the page is completely reloaded. I don't know why. has someone the same problem?

    thanks
    Yavuz

  45. sravanthi Says:

    how to adda row to the existing grid.

  46. Sid Says:

    What's the syntax to have jquery run a function BEFORE the DOM is loaded. Basically, i want to do the following BEFORE the DOM is loaded.

    1) Check a cookie
    2) Based on the cookie value i want to add a particular stylesheet
    3) Append the stylesheet TAG in the HEAD and then have the DOM load with the appropriate Stylesheet loaded.

    Creating the cookie and having the cookie load the appropriate stylesheet is not a problem, but how do I dynamically add a stylsheet to the html using JQuery ? The only way I can think of is to use some JQuery function that runs before the DOM is loaded, and i can't find what this mystery function is...

    perhaps you jQuery Guru's can help...

    thanks in advance,

    Sid

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <pre> <em> <i> <li> <ol> <strike> <strong> <ul>

IMPORTANT: If you wish to post code examples, please wrap them in <code> tags. Multi-line code should be wrapped in <pre><code> </code></pre> Also, use &lt; instead of < and &gt; instead of > in the examples themselves. Otherwise, you could lose part of the comment when it's submitted.