|
3 | 3 | ## Objectives
|
4 | 4 | + Set up a document.ready
|
5 | 5 | + Explain why document.ready is important
|
| 6 | + |
| 7 | + |
| 8 | +## Introduction |
| 9 | + |
| 10 | +We don't ever want to write our JavaScript and jQuery inside our HTML. For the same reasons that we want to separate out our CSS from our HTML, we want to separate out our JavaScript and jQuerys. |
| 11 | + |
| 12 | +But we had to write our JavaScript and jQuery code at the bottom of our HTML `body` so that the code would run once the page would load. How can we achieve that when our code is in a totally different file? We need to guarantee that the HTML document is loaded before our other files are triggered. |
| 13 | + |
| 14 | + |
| 15 | +## Separating and Linking Code |
| 16 | + |
| 17 | +If you take a look at `index.html`, you'll notice we have jQuery code written at the bottom. Our goal is to refactor this site to move that code out into `js/script.js` |
| 18 | + |
| 19 | +The first thing we need to do is link `js/script.js` to `index.html`. We do that inside our `head` tag with a relative link. Go ahead and copy the code below and paste it in `index.html` in between your opening and closing `head` tag. |
| 20 | + |
| 21 | +```html |
| 22 | +<script src="js/script.js"></script> |
| 23 | +``` |
| 24 | +Now that our HTML file can find our JavaScript File, it's remove the `script` tags from the bottom of our HTML file and move them to `js/script.js`. |
| 25 | + |
| 26 | +If you save all your changes, and open `index.html` in the browser, you shouldn't see the text `this is so freaking cool.` appear in the browser. That's because we haven't set the jQuery to run yet. |
| 27 | + |
| 28 | +## Document Ready |
| 29 | + |
| 30 | +Thankfully, jQuery has a built-in way to determine when a page is loaded. You'll be coding along in `index.html` and `js/script.js`. |
| 31 | + |
| 32 | +In `js/script/js`, we need to set up a document ready in order to detect when our HTML page has loaded, and the document is ready to be manipulated: |
| 33 | + |
| 34 | +```js |
| 35 | +$( document ).ready(function() { |
| 36 | + //code to be executed goes here |
| 37 | +}); |
| 38 | +``` |
| 39 | + |
| 40 | +The `$` is a shortcut that lets JavaScript know we're using the jQuery library. Every time you see `$` think jQuery. |
| 41 | + |
| 42 | +Once jQuery senses the document has loaded, the rest of the code will fire. Place the document ready around the jQuery already in `js/script.js`. Save your changes, and refresh in the browser. You should see the text appear in the browser! |
| 43 | + |
| 44 | + |
| 45 | + |
| 46 | +## Resources |
| 47 | + |
| 48 | ++ [Learn jQuery](http://learn.jquery.com/using-jquery-core/document-ready/) |
| 49 | ++ [jQuery Docs](https://api.jquery.com/ready/) |
0 commit comments