11/13 Why is it necessary put the "div" function inside the "document" function?


#1

Why does the whole "div" function have to be placed inside the "document" function?

$(document).ready(function(){
$("div").mouseenter(function()   
   {$("div").fadeTo("fast",1)
      });
   });

e.i. Why doesn't it work on its own?

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

 $("div").mouseenter(function()    
    {$("div").fadeTo("fast",1)
    });

#2

Hi Markrensen,

The $(document).ready(...); stuff is just a way to run some code once the page has loaded. It's only needed, if the link to your JS file is in the <head> of your HTML, which it normally shouldn't be, but it's good to have it just in case.
So, when you try to run JS code linked from the <head> without detecting page load first, what happens? Since the rest of the page hasn't finished loading yet, the JS will be searching for a <div> that hasn't come into existence on the page yet, so the code will throw an error and keep going. But it won't respond to you hovering it, since it wasn't able to find the <div>.

Does this make sense?


#3

Wow, that was such a good answer! Thanks. I was so far off with my thoughts; I was thinking functionality, but not at all about the bare essentials like loading sequence. It all makes sense now!

So codecademy always puts the JS link inside the head and it looks like this:

   <script type='text/javascript' src='script.js'></script>

What would it look like and where would you put it if you Don't write it inside the head?


#4

It'd look exactly the same as it does now (except that's an outdated syntax you've got), but just before </body>:

    <!-- other stuff -->
    <script src="script.js"></script>
  </body>
</html>

The type attribute is no longer required, since <script> tags aren't used for anything besides JS :)


#5

This only applies to JavaScript. It is now the defacto scripting language supported by most or all browsers. It is still possible to run other script (where supported) in which case the type attribute would be required to tell the browser what language it is; eg. VBScript


#6

@mtf Cool, I didn't know you could use other languages with <script>. It makes sense that you could, now that I think about it, though :)