Search code examples
javascriptjsfiddle

What is the difference between onLoad, onDomready, No wrap - in <head>, and No wrap - in <body>?


I use JSFiddle for editing my code. However, in certain codes when I'm running JavaScript or jQuery, it doesn't work unless I select "No wrap - <head>" or "No wrap - <body>".

JSFIDDLE HERE

In the fiddle above, you will notice that clicking the <button> element will not alert() you unless you've selected either the extension "No wrap - <head>" or "No wrap - <body>".

I'm a curious person who likes to understand how things work. What exactly does that option change, and why would you change it?


Solution

  • The onLoad and onDomready wrap the code so that the JavaScript runs when the document load or DOM ready events fire. It's as if your wrote your code like this:

    Stackoverflow Ref

     <script type="text/javascript"> 
        //<![CDATA[ 
          window.onload=function(){ /* your js here */ } 
       //]]> 
    </script> 
    

    The no wrap options are if you added your script tag to the head or the body tags of the document like how you're probably used to doing it.

     <html> 
     <head> 
           <title>Stuff</title> 
     <script> 
       /* your code */ 
     </script> 
     </head>