dynamically load content with jquery

Click on the titles to the three Shakespeare plays and notice that the quote on the right changes even though the page doesn't reload.

The content is being loaded dynamically using just a wee bit of jQuery.

Here's how it's done:

First of all you're going to need to install node.js and NPM:

How to install node.js and NPM on Windows

How to install node.js and NPM on a Mac

Follow the instructions on the Node website. This will install the node package manager(NPM). Once you’ve done that go to the command line and type…

npm install http-server -g

...to install the server.

Ok, now let's create a few simple HTML files and the jQuery to make this work. Place the following code in your index.html file:

<ul>	
<li><a href="home.html">home</a></li>
<li><a href="about.html">about</a></li>
<li><a href="contact.html">contact</a></li>
</ul>
<div id="content"></div>

Don't forget to include a link in your index.html file to your jquery-2.1.3.min.js (or whatever version they're on).

Now create three html files named "home.html", "about.html", and "contact.html". In each file place the word "home", "about", or "contact". Example

<p>home</p>

That's it. You don't need any other markup in the files. Just one line in each.

Now, the jQuery that makes it all happen. Create a new file and save it as loader.js(or any other name you want, of course). Place the following code inside it:

$(document).ready(function(){
    $("#content").load("home.html");

    $("a").click(function() {
    var page = $(this).attr("href");
    $("#content").load(page);
    return false;
    });
});

When the page loads, home.html will be loaded into the div with the id of "content". When a link is clicked the href attribute is saved in the variable "page" and then loaded into the div with the id of "content".

Ok, so on index.html are three links to home.html, about.html, and contact.html...plus the empty div with an id of "content". Your index.html should also have a link to jQuery and a link to loader.js which contains the code shown above.

Now, using the command line, navigate to the folder where you have saved all the files, type…

http-server

…and it will tell you where it’s hosted. (It will usually be localhost:8080.) Open up your browser and type that into the url area.

If you make changes, refresh, and then don't see them try this: Open up Chrome’s Developer Tools, click on the Network tab and check “Disable cache”. If that doesn't work try right clicking on the refresh button and selecting “empty cache and hard reload”. This only works if you have Dev Tools open though.

Have fun!

Elizabeth Hatleli


illustration of william shakespeare