Description:
This script allows us to load information from another file on our server without reloading the page. Essentially, we are loading a list of our favorite movies stored in a separate file on our server into this file when we click the anchor tag (or any designated element).
For more in depth usage, consider looking into creating an if else statement that checks to see what the text of the anchor tag reads. If the anchor tag reads 'Load Favorite Movies' then the script will load the movies when it is clicked and change the anchor tag text to 'Hide favorite movies'. Then the same anchor tag can be clicked again to hide the movies list, perhaps with a .remove method on the div#info.
View the source below for further comments and explanations.
Demo:
The Code:
HTML
<div id="container"> <p><strong>My Favorite Movies</strong></p> </div> <a href="post_icons.htm">Load Post Icons</a>
jQuery
<script type="text/javascript">
$(function() {
$('a').click(function() { // run the following function when the anchor tag is clicked
$('<div id="postIcons" />').load('post_icons.htm #iconsList', function() { // we are creating a div with an id of 'info' (we are creating the div here since we are including <> as opposed to calling to a div with id info already created). Then within that div we are loading the element with id of movies (#movies) within the file called new_file.html. We then run a function within the load method (called a callback function --> runs right away once all the information we previously designated has loaded...in this case, we will run the funciton once all the info in #movies has loaded) to cause the list to animate in as it loads.
$(this).hide() // first we hide this div so that we can slide it down otherwise it will just load instantly.
.appendTo('#container') // this is appending the div we are creating to the container div already in the DOM
.slideDown(1000); // and findally, this is sliding the div down over the course of 1 second
});
return false; // we add this to disable the default functionality of the element we are targeting (in this case the a). This allows us to link to new_file.html in 'a href=""' so that in case they have javasript turned off, it will just take them to the page to display the list of movies, but if javascript is on, it will disable the default functionality of the a linking to the new_file page and will run our script.
})
});
</script>