0

I just recently started learning about web-design and I've reached the part where I need to learn to import APIs and JSONs into my pages. Anyway, I've been using codepen.io to practice so far, but I wanted to try out with some JSONs created by me - meaning I'd have to write my code in notepad++ -. Long story short, I can't even seem to be able to import jQuery into my .html file. I have the code below:

<!DOCTYPE html>
<html>
    <head>
        <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js'></script>
    </head>
    <body>
        <script>
            $('button').click(function () {
                $('div').fadeTo('slow',0);
            });*/
        </script>
        <button>Hello</button>
        <div>HELLO</div>
    </body>
</html>

Normally, this would make the HELLO div disappear, but it doesn't. Also when I look into the console of my browser (F12) it says that the google server has returned a 304 code.

j08691
  • 190,436
  • 28
  • 232
  • 252
KostasKol
  • 111
  • 1
  • 9

1 Answers1

2

At the time the script executes the <button> element doesn't exist in the DOM. The $('button') returns an empty collection, and no event handlers are bound.

You'll need to do one of the following:

  • move the script to execute after the DOM nodes that the script depends on have been created
  • wrap your code in a call to document.ready:

    $(function () {
        ...your code here...
    });
    
  • add the defer attributes to the script element so that it executes after the rest of the DOM has loaded.

  • delegate the event handler so that it's bound to a parent of the future nodes:

    $('body').on('click', 'button', function () {
        ...your code here...
    });
    
zzzzBov
  • 157,699
  • 47
  • 307
  • 349
  • Ok, I get it now. I usually use the $(document).ready function. I seriously can't believe I just forgot to use it. Thank you very much. Have a good one :D – KostasKol Mar 10 '16 at 19:52