Introducing $(document).ready()

read 140 comments

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.

  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().

Continue Reading Below

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.


I thought it might help the absolute beginners to see an example of the <head> where you would include your scripts. Note that CSS stylesheets come before the jQuery file, and the jQuery file comes before your custom script:
  2.  "">
  3. <html lang="en">
  4. <head>
  5.   <meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
  6.   <title>your title</title>
  7.   <link rel="stylesheet" type="text/css" href="styles/forms.css"></link>
  8.   <script type="text/javascript" src=""></script>
  9.   <script src="yourcustomscript.js" type="text/javascript"></script>
  10. </head>
  11. <body>
  12.   <!-- the body of your document goes here -->
  13. </body>
  14. </html>

It is in "yourcustomscript.js" that you would place your script inside the $(document).ready() block.

comment feed


  1. 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 :-)

    • E-Scaping

      I think for the purpose of being a complete beginner and learning JQuery from the very start (like myself), learning code in a strict, long hand manner is definitely the best way to be taught, especially in my experience.

      Only when you are bordering on intermediate level should you be looking into shorter and easier ways of accomplishing the same effects. Plus, it gives us noobies a better understanding of the syntax rather than being left wondering.

      • Ken Haley

        I'm a jQuery beginner too. However, I value the knowledge of shortcuts mainly because it helps me understand sample code. I can't tell you how many examples I looked at using the shortcut version of $(function(){ }) as an abbreviation for the $document.ready() block before I realized that I was even looking at a shortcut. Everything said, startup code must be inside 'document.ready' blocks, but none of the samples did it. I finally figured it out. That's something that NEEDS to be documented for newbies.

        • Lapin

          @Ken Haley : +1 ;)

          I didn't know before i read you $(function(){}) was an abbreviation... But i saw it many times and i didn't know what to do with this!
          Thanks :)

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

  3. 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. 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?

    • Carlos

      Hello Karl, I am having the display flashing problem when I .hide() and .show() at document.ready(). Have you find the solution to avoid that?. I obviously can't hide via css, because there are galleries that don't work if I do that. Please help!!


  5. 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. 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

    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

    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

    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


  10. 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. 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. 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


    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() {
    		vertical: false,
    		start: 1,
    		size: 4,
    		itemWidth : 100,
    		itemHeight : 100,
    		itemVisible: 1,
    		itemScroll: 0,
    		nextButtonStateHandler: 'prev',
    		prevButtonStateHandler: 'next'

    Thanks for all,

  14. 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

    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

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

    I think the frameReady does what you're looking for.

  17. 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

    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. Hi Darren,

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

  20. Kevin

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

  21. Fred

    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. 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

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

  24. sunil

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

  25. 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


    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. I recommend that you bring this up to either the jQuery discussion group or the jQuery Dev group.

  28. PAStheLoD

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

  29. Ing Angel Lacret

    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. Ing Angel Lacret: I'm not sure if I'm understanding your question correctly, but I think this FAQ item should help.

  31. 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 $

    		$(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

    Thank you all in advance...

  32. Greg


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

  33. Greg


    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. 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. 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

    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. 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. 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. Hi Eirik,

    In the 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. sweet, thanks Karl that's just what I need.

  41. cybercow222

    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. 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

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

  44. 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() {
      		  type: "POST",
    	      url: "ajax.tasklist.php",
    	      dataType: "html",
    	      beforeSend: function(){$("div.loading").show()},
    	      complete: function(){$("div.loading").hide()},
    		  success: function(msg){
    	function save() {
    		alter ("hallo");		

    in the html part the following elements

        <a href="">save</a>
        <a href="">Link</a>

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


    • Although my code is slightly different than yours, Yavuz, it's pretty similar, so I have the same problem as you... and no solution. I thought that @epikarma below had the same issue, but alas, it's a different one, so we're both without a solution for now...

      Apparently, what happens is that if you have a callback for AJAX, if the code inside it somehow changes an element on the page (in your case, show() and hide() — I've tried with other things like setting button attributes to "disabled" and enabled again), after the callback is called, it triggers $(document).ready() again. Why? I have no idea! How to prevent it from getting triggered again? Once more, I have no idea: it's hard to devise a callback that does absolutely no change on the page (even an alert!).

      Worse, when the page refreshes, obviously all the information I had on a form is naturally lost... exactly the reason why I had resorted to jQuery/AJAX to eliminate page refreshes!!

      • Hi Gwyneth,
        It's hard to answer the question in the abstract, but if the page is refreshing, you're probably running the ajax function inside an event handler for an event that has a default action. For example, if you're trying to perform an ajax request when the user submits a form, the form will still be submitted (and the page will refresh) unless you explicitly prevent the default action. One of the easiest ways to do that is to add return false; at the end of your event handler function. Does that make sense? Please clarify if I haven't understood you correctly. Also, you might want to post the question, with details and a demo page if possible, to the jQuery Google Group.

    • I have indeed the same problem, and it seems that the "page refresh" comes from a default handler being called somewhere... I've read that all these callbacks ought always to return false to make sure that the standard behaviour is never called.

      Sadly, no matter how many return falses I put on my code, it still does a refresh. Mind you, I have way more callbacks, and one of them is very likely misbehaving at some point, but it seems almost impossible to track down...

      Also, my purpose was to avoid page refreshing on a form and thus using jQuery/AJAX... sadly, not only I get exactly what I was trying to prevent from happening, but, even worse, on the call properly the page not only refreshes but deletes all form contents, making it pretty useless.

      Debugging this is way hard for a poor beginner like me :( I'm happy that I'm not the only one, but I was expecting this to be something way easier to fix.

      • Yes, I understand the problem you're having, but like I said before, it's hard to answer this question in the abstract. Can you put a test page somewhere public so I can take a look at what you're doing? If not, post your question to the jQuery Google Group and be sure to include the code that you're trying to use.

      • Ok, whew. After some endless hours around this, I found out two major problems with my code. This might be useful for others, too.

        First, if it's not obvious for you: put return false; on all your functions and callbacks. This will prevent any "default handler" to inappropriately submit your form. Although this is easily overseen, it's truly mandatory. I can imagine that every expert jQuery programmer will, by now, be sniggering and saying "of course you have to return false, every kid in school knows that!". Alas, for a beginner, this is anything but obvious.

        This might very likely also fix Yavuz' code above.

        The other not-so-obvious issue is that callbacks can be placed inside $(document).ready(function() {}), but that is only a good idea if they're very simple and if you can be absolutely sure that they will be called when inside the scope where they're declared. Anonymous functions are cool and I can see how they can be easily overseen for what they are: limited to the scope they appear. In my case, I had been too optimistic about their persistence. Moving them outside the ready() block made things finally start to work for me.

        In any case, my feeling is that there are two kinds of tutorials all over the Web about jQuery, but they fall neatly in one of two cases: examples for absolute beginners (we all need to start somewhere), and technical references for experts. It's for the slightly-not-so-beginning developers that things become tricky, since the "references" are only partially interesting (if you know how things work and just need to quickly look up the proper syntax).

        On the other hand, if we didn't have Google, I would have never found out about this, hidden deeply in a forum somewhere. Oh, yes, the jQuery documentation actually mentions the issue about return false, but it's only understandable... after you know what it is for :)

  45. how to adda row to the existing grid.

  46. Sid

    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,


  47. Amol

    Nice Article! I really liked it.
    This is a really good tutorial!

  48. Ken

    Could anyone help me find out why my jquery does not work at my site, even when I copy the source code from other working sites and paste into my page?


  49. Hi Ken,
    I don't see a reference to the jQuery core file. Make sure you put that in there before your reference to the corners plugin. You can download the latest version of jquery.js from

  50. voyager

    @Chris Ovenden:
    is your friend.
    You can make a css file include that is only used *if* there is no javascript available, so you could hide the whole document by default, and import a css file that shows the needed elements when scripting is not available, making the site usable again.

    Disclaimer: I haven't used this technique, so I can't assure that it works as expected cross browser. YMMV.

  51. voyager

    Sorry, that was suposed to be "<noscript> is your friend"
    Didn't see the preview...

  52. voyager

    It was suposed to be "<noscript> is your friend"

  53. epikarma

    I don't understand why this code doesn't work.
    First example works, but when I try to wrap calling to $.ajax, WNPostback function is called automatically when page is loaded and not on the click of my btnHour2 button.

    First example
    $(document).ready(function() {
    	$("#btnHour").click(function() {
    			type: "POST",
    			url: "DefaultJson.aspx/GetDate",
    			data: "{}",
    			contentType: "application/json; charset=utf-8",
    			dataType: "json",
    			success: function(msg) {
    Second example
    var btnHour2Click = WNPostback("DefaultJson.aspx/GetDate", "{}",
    	function(msg) {
    function WNPostback(urlMethod, dataParam, callbackSuccess, callbackError) {
            type: "POST",
            url: urlMethod,
            data: dataParam,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: callbackSuccess,
            error: callbackError
    $(document).ready(function() { $("#btnHour2").click(btnHour2Click) });	
  54. epikarma, try:

    var btnHour2Click = function() {
    WNPostback("DefaultJson.aspx/GetDate", "{}",
    function(msg) {

    function WNPostback(urlMethod, dataParam, callbackSuccess, callbackError) {
    type: "POST",
    url: urlMethod,
    data: dataParam,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: callbackSuccess,
    error: callbackError

    $(document).ready(function() { $("#btnHour2").click(btnHour2Click) });

  55. oops.

    epikarma, try:

    var btnHour2Click = WNPostback("DefaultJson.aspx/GetDate", "{}",
    	function(msg) {
    function WNPostback(urlMethod, dataParam, callbackSuccess, callbackError) {
            type: "POST",
            url: urlMethod,
            data: dataParam,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: callbackSuccess,
            error: callbackError
  56. holy shizat. I pasted the wrong thing the 2nd time and din't notice the live comment preview.

    Oh well. Point was, epikarma, don't set something to a named function with parentheses unless you want to execute it. Rather, set it to a wrapper function which itself invokes your function.

  57. epikarma

    It works.
    If I understand well the instruction
    var btnHour2Click = WNPostback(...
    means that I attribute the result of WNPostback to btnHour2Click var instead the function.
    Ok now it's clear.

    Thanks Jon.

  58. Hi I am trying some basic stuff on my website like Hide()
    i have add the following code on my page

    @import url("");

    $(document).ready(function() {

    but when i try to open my site it wont work and firebug shows the error
    $ is not defined
    (?)()blog (line 13)
    [Break on this error] $(document).ready(function() {

  59. That error is almost always caused by a missing or incorrect reference to the core jQuery file. Before you reference your custom script, you need to reference jQuery. So, in the <head> you might have something like this:

    <script type="text/javascript" src=""></script>
    <script type="text/javascript" src="/scripts/custom.js"></script>

    Then put your three lines in the custom.js file

  60. Hello, I am trying to use Christian Bach's table sorter on a page which is itself is being built from a PHP script (called using pure AJAX and through jquery).

    Everything works well, but only when the HTML is embedded: ( NOT when the table is built dynamically from the database: ( HOWEVER, the debugger alerts the correct HTML loaded, and the compiled HTML (using Firebug) shows identical code between the two versions (embedded vs. dynamic).

    I have tried:
    1. executing the innerHTML fetch onload=
    2. and $(document).ready. (i.e. with and without jquery);

    3. a php print() of the whole table,
    4. and just of the <tr><td/> tags

    5. referencing the object id in the HTML
    6. and when print()'d using PHP

    7. and most combinitions of all of these...

    any ideas, insight, and/or direction would be huge!?

    thanks in advance!?


  61. Rico Chen

    For those who have "'jQuery is not defined" or "'$ is not defined" problems, you might need to check if you are using some content filtering proxy (dansguardian for example). I had this problem after I configured and started dansguardian on my firewall server.

  62. Colin Elligsen

    This is my first attempt at jquery and it is driving me nuts.

    What is wrong with the following code?

    <script type="text/javascript" src="jquery.js"></script>
    <link rel="stylesheet" media="screen" type="text/css" href="css/colorpicker.css" />
    <script type="text/javascript" src="colorpicker.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
    $('#topmenutextcolor').ColorPickerSetColor({flat: true});
    <p id="topmenutextcolor">

    Please forgive me if this is the wrong place to post this.

    Colin Elligsen

  63. Colin Elligsen

    Sorry about the bad formatting, here is the code that doesn't work. It is my first attempt at jquery and it doesn't work, but neither does it give any errors. The files are all in the right places. I only pasted the relevant code there is a start head tag for example before this code.

    See also:

    <script type="text/javascript" src="jquery.js"></script>
    <link rel="stylesheet" media="screen" type="text/css" href="css/colorpicker.css" />
    <script type="text/javascript" src="colorpicker.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
    $('#topmenutextcolor').ColorPickerSetColor({flat: true});
    <p id="topmenutextcolor">
    • Theodore Ni

      I have not downloaded the code, but the documentation may have a typo. You should try
      $('#topmenutextcolor').ColorPicker({flat: true});

  64. prashant


    I want to know, can we use this ready function more than one time in a page.

  65. I have a problem with the tabs that have tables where the UL LI is shown to the user, then after the page finishes loading it creates the tabs

    Not very professional looking!

    How do I fix this?

  66. Robbie

    Hi there, i know its late 4 posting here, hehehe, anyway, hope someone reads this doubt i have...

    after using $(document).keypress.....i would like to know if i can "cancel" document from waiting for the keypress it possible ?


  67. Escort

    Its amazing what you can achieve with jquery. Thanks for the tip.

  68. Wolle

    I'm using jqModal and therefore I used for loading:

    $().ready(function() {
    $('#d-projekt').jqm({overlay: 88, modal: false});

    Everything is working with one function, but if I'm using jqModal twice or more often like #d-projekt and #isaak_loewi - all the actions are appearing at the same time:

    $().ready(function() {
    $('#d-projekt').jqm({overlay: 88, modal: false});
    $('#isaak_loewi').jqm({overlay: 88, modal: false});
    $('#true_destination').jqm({overlay: 88, modal: false});

    I'm not sure how to load it in the right way:-(

  69. asaaki

    Why is it that a page works fine with jQuery and a number of different jQuery plugins, and then when I include one more plugin - jCarousel - I suddenly get the error that jQuery is not defined? And that $('#mycarousel').jcarousel() is not a function? I've been at this for two days in vain.

    I've tried replacing all instances of "jQuery" with "$" in jcarousel.jquery.js, but while it no longer says that jQuery is not definted, jcarousel() is still not a function. And yes I am pointing to the correct path =S

    I've been able to work all plugins together successfully when I work on my local machine but as soon as I upload it, it stops working.. As soon as I comment out the single line $('#mycarouse').jcarousel(); everything works fine again. Any ideas why this happens?

  70. Deepak

    How could write unobtrusive scripts for html rendered by ajax ?
    Lets say, we a web page index.php. After it loads and the user clicks on a button , an ajax call is triggered which creates a new div whose id is "division" on this web page.
    How can I write an event handler something of this sort
    $('#division').hover(function(){$(this).css({'background-color' : 'yellow', 'font-weight' : 'bolder'});});

    But this wont work , because this part of the DOM was not ready upon document.ready

  71. bogdan

    i am using this to update a chatscreen but it doesnt work ... it only shows the div content, it doesn't replace it ... any ideas?


    function updateMsg() {
    url: "/messages",
    cache: false,
    success: function(html){
    setTimeout('updateMsg()', 4000);

  72. Do you recommend putting the $(document).ready() in an external .js file?

    Similarly, if you do or don't, should the call to the $(document).ready() file go at the bottom fo the page right before the closing BODY tag?

    I think the answers to those questions would be a great additions to the official jQuery FAQ, by the way, Karl. Not sure if you have access to that or not.


  73. Veeru

    Hi Karl,
    its a very good article and i like reading your articles.
    I have a small question though... what if the user manipulates the dom before its even loaded, is there a way to prevent it?
    For example, i have attached an event to a button/link on dom ready, but how can i stop the user from interacting with the page before the dom ready is completely executed? I do not want the user to interact with the page till its completely loaded.

    Any ideas?


  74. Hi Karl,
    I am getting a very strange error. I build a wordpress theme that make use of jQuery. All works fine on my computer. But once loaded into the server I get the error.

    Line: 32
    Error: Object Expected

    which contains the code


    My debugging efforts makes me conclude that the above code is executed before the attached jquery file is downloaded by the browser. I have checked the path to the jquery library. If I call the jQuery file form a local server it works fine. My hosting server is abroad and hence slightly slower.
    Have you ever come across such an issue. please advice.


    • Hi Alfie,
      It's hard to know what the problem might be without seeing the actual page. Which browser are you using? Does the error occur in different browsers? Do you have a link to the page that contains the error? Scripts are blocking, so as long as you include the jQuery file first, the other one shouldn't load until jQuery has finished loading.

  75. Arun Kaur

    I saw just now
    it’s very supported attempt….
    thank you zamshed.

  76. Great threads here, hoping you can offer some insight. I'm trying to call a jquery function to launch prettyPhoto (lightbox clone) with document.ready, and pass all the necessary parameters:


    The normal syntax is:

    a href="mypage.html" rel="prettyPhoto" title="photo caption"

    If anyone can help, that would be greatly appreciated. Thanks!

  77. Started learning jquery. Nice first tutorial to start with.

  78. Arun

    We are using in our application. I'm facing an problem with events. We have many <a> tags and buttons our page which is listening to a click event. Click events for these tags are binded outside like below code:

    $("#link1").bind("click", method1);
    $("#button1").bind("click", method2)

    As above code all events for my dom elements are associated outside ready method. When page is loaded is these dom element events are binded or not?

    • Hi Arun,

      There are a couple problem there. First, $(document).onReady(function(){ should be $(document).ready(function(){. Second, you're hunch is correct that the event handlers won't be bound.

      Try using the .live() method instead, especially if you're binding to a lot of links. Since .live() actually binds to the document itself and uses event delegation, you don't have to put that code inside a document ready block. This tutorial might help.

      • Arun

        Thanks for reply. I have lot of links and buttons in my page, do i need to change all bind method to live method? or is there any other way do it?

        if yes, When to use bind method and live method?

  79. Lucy

    I am new to JQuery. If I have javascript func1() code in $(document).ready(function(){})
    and just before </html> I have javascript func2(). which code will be run first? func1 or func2?

  80. skylar

    Honestly i still don't get it, this seems more like "theory" vs. "best practice"....and by "best practice" i mean only in the blog-o-sphere.

    Most large scale sites (flickr, wiki, yahoo, google, apple, digg, sites in alexas top 100) DON'T use this method AT ALL! they just use straight inline javascript, for example, the pioneers of ajax, use inline javascript all over the place.

    Which leads me still wondering, "document.ready()" "why?", which is what lead me to google my question land jqeury's site, then redirected here...still wondering "document.ready(), why?"

  81. Alexandros

    Hello there!
    I am using jquery-1.3.2.min.js and jquery.history.js to keep navigation of my website while using ajax to change the content of my site. However, it seams that IE and Chrome don't like it. First time the page loads the content of the home page is not displayed (a refresh is required) on both browsers, Chrome is flashing the content several times before finish displaying it and IE is moving the screen at the link clicked. Please help me out if you can. See code bellow:

     <script src="jquery-1.3.2.min.js" type="text/javascript"></script>
            <script src="jquery.history.js" type="text/javascript"></script>
            <script type="text/javascript">
                var query = "NULL";
                var hidden = false;
                function loadPage() {
                    //Check if url hash value exists (for bookmark)
                    if(document.location.hash == '')
                        document.location.hash = '#Home';
                    //highlight the selected link
                    $('a[href=' + document.location.hash + ']').addClass('current');
                    $('span[id=' + document.location.hash + ']').addClass('current');
                    //Search for link with REL set to ajax
                    $('a[rel=ajax]').click(function ()
                        //highlight the selected link
                        $('a[href=' + document.location.hash + ']').addClass('current');
                        $('span[id=' + document.location.hash + ']').addClass('current');
                        //grab the full url
                        var hash = this.href;
                        //remove the # value
                        hash = hash.replace(/^.*#/, '');
                        //for back button
                        //clear the selected class and add the class class to the selected link
                        //hide the content and show the progress bar
                            hidden = true;
                        //run the ajax
                        //cancel the anchor tag behaviour
                        return false;
                function pageload(hash)
                        hidden = true;
                    //if hash value exists, run the ajax
                    if (hash) getPage();
                function getPage()
                    //generate the parameter for the php script
                    if (document.location.hash=='')
                        var data = 'page=' + encodeURIComponent('#Home');
                        data = 'page=' + encodeURIComponent(document.location.hash);
                        if(query != "NULL")
                            data = data+query;
                        url: "loader.php",
                        type: "GET",
                        data: data,
                        cache: false,
                        success: function (html) {
                            //hide the progress bar
                            //add the content retrieved from ajax and put it in the #content div
                            //display the body with fadeIn transition
                            hidden = false;
                function submitForm(form)
                     query = "&" + getForm(form);
                        hidden = true;

    Thanks in advance!

    • Hi Alexandros,

      I'd love to help you, but my time is limited right now. Perhaps you could direct your question to the jQuery Google Group. I think you'll have a much better chance of getting a satisfactory answer and will be able to follow up with additional questions more easily. Please describe as clearly as you can the outcome you're trying to achieve and show the code that you have written so far.

  82. I have started learning jquery. this has helped me. thanks

  83. $(document).ready(function() { } 


    $.function() { }


    help me..

    bali web programmer

  84. dynamically on a page How do I change the data in iframe?

  85. The Opera download the html and css will not in the same time,so it happened that we see some pages with no "css",can it be soloved?Thanks.Please reply me,by email better.

  86. Andy

    I keep getting $('document') .ready undefined.

    i load jquery....js before this is executed. So this is not about it.

    $(document).ready(function() {


    firebug keeps reporting error $('document').ready undefinded. Adding watch $(document) it is as it should be, for some reason $(document) is turned to $('document')

    Any ideas please help quick.

    I use jquery-1.3.2.min.js

  87. You said that CSS loads before jQuery ... Is that the case to do so in any project? To load CSS before JS Files?

    • I recommend that you load your stylesheets before your JavaScript files, so that any JavaScript that relies on the way things are displayed on your page can have access to that information.

  88. Epic. JQuery to the rescue. Another great function that I use a lot is:

    $(window).load(function () {
    [your code in here]

    Whats different with this function? It actually waits until all scripts, images, etc finish loading.

  89. I use jQuery for quite some time. I wanted a refresh and starting from zero. The discussion in comments is very interesting and author Karl is very helpful in replying readers questions. Thanks Karl

  90. Thanks! another learning planted on my memory... this is a good start for my jquery quest. :)

  91. but i have included


    $('#slider-code').tinycarousel({ pager: true });


    this code in head, but still getting the error " $ is not defined"

    • Are you referencing the jQuery core file before your custom script? If so, are you sure you have the correct path? Try putting a script tag that looks like this before your other scripts:

      <script src=""></script>

  92. nikl

    What is the differene between
    jQuery(document).ready(function($) {
    $(document).ready(function() {

    • Ankit

      After some googleing....
      There is no difference.

      $ is the same as jQuery. If you view the unminified source, you will see var $ = jQuery = ... or something to that effect.

      The jQuery function checks the type of it's parameter, if it is a function, it treats it the same as $(document).ready(...)

      Calling jQuery without a parameter defaults to using document. So $() and $(document) are identical. Try it in Firebug.

  93. Dave

    I a calendar page on my site, and I'm trying to refresh the containing div only when submitting a new date.

    I am using this to refresh the div on a main page:

    function DoDate(gDate)

    And in the caldiv.asp page I am using:

    fDate =  Request.QueryString("fDate")

    The div refreshes fine, but no data is passed.
    I tried $('#caldiv').load('caldiv.asp?fDate=' + gDate).fadeIn("fast");
    But that didn't work either...
    How do I get this to pass the new date to the div page?

  94. Billy Brinkley

    Fixed my problem. With out it my call to open the jQuery modal dialog would not work.

      $(document).ready(function() {
  95. Andy

    Hi Karl,

    while reading Cody Lindley's jQuery Enlightenment I am wondering if it is correct to say, that you don't need the ready() function, if all the JavaScript code is placed just before the closing tag. I had some discussions about that, and there are different opinions what leads to the position better using the ready() method. So are there any cases in which there is a need to use the ready() function also here:

    ... DOM ...
    <script src="/path/to/jquery.js"></script>
    <script src="/path/to/all-javascript-compressed-in-one-file.js"></script>

    So is there a need to use ready() inside the scripts in all-javascript-compressed-in-one-file.js? As far as I am concerned, I don't need to use ready() in this case at all.

    How about performance advantages using ready()?

    Thanks for pointing this out ...



  96. Can any one please explain what is $ in jQuery ? is it just alias of jQuery and also when i should used jQuery instaed of $. ?

  97. Billy bureua

    What is the difference in the whole documentReady versus window/document.load? And what's this business that the javascript calls should be put just above the closing html tag so that all is loaded before the javascript.

    I've heard the document.onLoad is what is really needed to actually manipulate any elements on the page once they are actually available?

    • Pierre

      Hi Billy,

      The document.ready() fires when your DOM (your webpage tree) is loaded, but not the content of your page.

      Therefore, the window.load() function fires when everything on your page has been loaded.

      So you can use the first one when you're manipulating text, css and html, but you absolutely have to use the second one when you manipulate heavy stuff such as pictures.

      I hope i 'd been helpful.

  98. Sorry, I tried to read all the comments, to see if my question had already been asked, but my eyes started to

    Just wondering, when it was said "all your jQuery goodness here", does that mean that I need to structure my code so that every function that I have created that uses a jQuery method or function should go inside the .ready()?

    • Pierre

      Hi Rob,
      you have to call your 'jQuery Goodness' inside a $(document).ready or $(window).load depending of your goodness.

      But your functions can be far away from this tags.

      This is an exemple :

      function putText(){
      $(body).html('hello world!');


  99. David

    Hi, i use buttons with . Alwaays when clicked on one of these buttons, the document.ready is executed again (FF and IE). Is there a way to get rid of the repeated execution?

    • I'm guessing that you're binding a click handler to links (<a>). If so, you need to either return false at the end of the function or pass in the event object and call event.preventDefault().

      Your code should look something like this:

      $('findSomething').bind('click', function() {
        // do something
        return false;

      or like this:

      $('findSomething').bind('click', function(event) {
        // do something

      You will, of course, need to replace 'findSomething' with the real selector and replace the // do something comment with your real code.

      p.s. Looks like you didn't escape the < and > in your comment.

25 Pings

  1. [...] la chiamata al nostro helper nell'evento "document ready" di jQuery in modo da costruire la griglia al momento [...]

  2. jQuery Fling | Command-Tab

    [...] use jQuery’s handy document ready to set up new Fling subscribers, and then publish the [...]

  3. An nice & simple AJAX Username Checker

    [...] of the first things that you should learn about JQuery is the usage of $(document).ready(): This is the first thing to learn about jQuery: If you want an event to work on your page, you [...]

  4. [...] Introducing $(document).ready() » Learning jQuery - Tutorials and Information [...]

  5. [...] above pushlog.tmpl code is placed inside $(document).ready(). As you can see I basically hide all the files touched data on line 40. Then, I go through each [...]

  6. [...] new code. Lots of changes to look at it. First of all the JavaScript code has been shifted within $document.ready(). The major changes have occurred in loadEntries(). The jquery library makes it extremely simple to [...]

  7. [...] event handler of either the window or body HTML DOM objects in JavaScript — except that $(document).ready() does not require us to hard-code it into an XHTML [...]

  8. [...] ir al código que hará que todo se conecte. Debajo de todo (aunque tengo teorías de que con un $(document).ready() de jQuery seria lo mismo) ponemos [...]

  9. [...] For more infomation: Introducing $(document).ready() [...]

  10. [...] Il codice di jQuery deve sempre iniziare con il costrutto $(document).ready(), per segnalare alla pagina di eseguire il codice quando tutto il contenuto è caricato: [...]

  11. [...] Introducing $(document).ready() » Learning jQuery – Tutorials and Information [...]

  12. [...] You can read more about it : Introducing $(document).ready() [...]

  13. [...] You can read more about it : Introducing $(document).ready() [...]

  14. Hvem glor – din bror » ASP.NET Ajax asynkront postback jQuery problem

    [...] $(document).ready() bliver normalt kaldt, når DOM er klar til at blive manipuleret, men det sker ikke efter at et [...]

  15. jQuery cannot cook | I-Am-Bot

    [...] Now one of the most important features of jQuery - the $(document).ready() function. What it basically does is it allows us to run our Javascript stuff as soon as the DOM is ready, and does not wait for the entire page to load (including images, and other resources which might be time consuming). This means that our scripts can execute a bit faster when compared to using the traditional window.onload method. More on that here and here. [...]

  16. [...] to jQuery then you need to start by understanding $(document).ready(). You can read all about it here. But the bottom line is that everything inside this method will load as soon as the DOM is loaded [...]

  17. Difference between $(document).ready(function(){}); and $(window).load(function(){});

    [...] you want to know more about this, you can visit one good site named “learningjquery“. Karl Swedberg has explained clearly about the same with an example of how to start coding [...]

  18. [...] inside the document ready function gets executed when jQuery determines that your document is fully loaded. This is an [...]

  19. Small Tips Using WordPress and jQuery | Best Wordpress News™

    [...] To check whether the HTML is loaded, use the following call. That makes sure that the DOM is loaded and you can browse the DOM via jQuery and now the real work of the script can start. I strongly recommend to use this variant. I don’t want to explain all the benefits, but you can read about it in the article Introducing $(document).ready(). [...]

  20. Small Tips Using WordPress and jQuery » WordPressURLs

    [...] To check either a HTML is loaded, make make make make make make make make use of of of of of of of of a following call. That creates certain which a DOM is installed as well as we can crop a DOM around jQuery as well as right away a genuine work of a book can start. we strongly suggest to make make make make make make make make use of of of of of of of of this variant. we do not wish to insist all a benefits, though we can review about it in a essay Introducing $(document).ready(). [...]

  21. How to: Resolve $(“ul.sf-menu”).superfish and b.isEmptyObject is not a function Error - Developer Snippets

    [...] If you would like to know more about $(document).ready(function(){}); – click here and if you would like know when to use $(window).load(function(){}); – click here to [...]

  22. [...] syntax for jQuery. If you are using jQuery, you can use $(document).ready() instead of the body’s onload event and the checkJS() function. All you need to do is add this [...]

Sorry, but comments for this entry are now closed.