Advertisement
  1. Code
  2. JavaScript
  3. jQuery

How to Load in and Animate Content With jQuery

Scroll to top
Read Time: 8 min

Clicking on any links on a webpage usually loads the content of that URL in our browser. This is how most links and websites on the internet work. However, you can also change this default behavior with a little bit of code to load the content of the new URL in a specific element within the current webpage without reloading the entire page.

This is possible with the help of a little bit of JavaScript. We will be using the jQuery library to do the heavy lifting related to animation and AJAX content loading.

You can also load in and animate content with vanilla JavaScript.

Preparing the Markup

We will be using a very simple webpage to demonstrate how the effect works. However, the principles you learn here will apply to other websites as well. Here is the markup of the homepage of the website that we will be loading in and animating.

1
<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
    <meta charset="UTF-8">
5
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
6
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
7
    <title>Home</title>
8
    <link rel="stylesheet" href="style.css">
9
</head>
10
<body>
11
    <nav>
12
      <ul>
13
        <li><a href="index.html">Home</a></li>
14
        <li><a href="about.html">About Us</a></li>
15
        <li><a href="team.html">Our Team</a></li>
16
        <li><a href="contact.html">Contact</a></li>
17
      </ul>
18
    </nav>
19
20
    <span class="loader"></span>
21
22
    <section id="content">
23
        <img src="dog.svg" />
24
25
        <h1>Embrace Pawsitivity, Transform Lives!</h1>
26
27
        <p>Welcome to Pawsitive Care Foundation, a dedicated organization working towards the well-being and protection of animals.</p>
28
29
        <p>Our animal Welfare NGO provides a range of services to support animal welfare:</p>
30
31
        <ol>
32
            <li>Rescue and rehabilitation of abused and abandoned animals</li>
33
            <li>Adoption programs to find loving homes for animals in need</li>
34
            <li>Education and awareness campaigns to promote responsible pet ownership</li>
35
            <li>Lobbying and advocacy for stronger animal protection laws</li>
36
            <li>Collaboration with local communities to implement spay/neuter programs</li>
37
        </ol>
38
    </section>
39
40
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
41
    <script src="load-content.js"></script>
42
</body>
43
</html>

The markup links to a style.css file which contains the CSS for styling all our webpages. The body of the webpage contains a nav element with a list of links that the users can visit. There is a span element with the loader class. We will be showing and hiding this loader element whenever users click on one of the links in the navigation. This loader will indicate that the loading of the page is currently in progress.

After that, we have a section element with id set to content. Every webpage of our website will have this section. The content inside this section is what we will be loading using AJAX. We also have two script tags near the end of our body element. The first script tag loads jQuery, while the second one loads our own JavaScript file.

Here is what our page looks like with the help of a little bit of CSS:

AJAX Website HomepageAJAX Website HomepageAJAX Website Homepage

You can create similar pages named about.html, team.html, and contact.html.

Styling the Loader and Content

We will now learn how to use CSS to animate our loader so that it keeps spinning whenever we are in the process of loading new content. Here is the CSS that keeps our loader spinning.

1
 .loader {
2
   background: white;
3
   width: 30px;
4
   height: 30px;
5
   display: inline-block;
6
   position: absolute;
7
   right: 2rem;
8
   top: 1.2rem;
9
   animation: 0.5s infinite spin;
10
   border-radius: 50%;
11
   border-top: 5px solid black;
12
   border-bottom: 5px solid gray;
13
 }
14
15
 @keyframes spin {
16
   0% {
17
     transform: rotate(0deg);
18
   }
19
   100% {
20
      transform: rotate(360deg);
21
   }
22
 }

There are a few things to note here. First, the loader has absolute positioning. This takes it out of the normal flow of the document so that we can place it wherever we want, without disrupting the flow of other content.

We use the animation property to animate our loader continuously according to the spin keyframe values, where each animation loop is completed in 0.5s.

The use of border-radius: 50% makes our loader round because it has the same width and height. Using different border colors at the top and bottom is simply a styling preference.

We will also use the following CSS to make sure that the content we are loading covers the whole width of the body.

1
section#content {
2
   width: 100% !important;
3
}

This will become important later when we animate the main content.

How you want to style the general content on all these webpages is up to you.

One thing that you will notice if you load any of the webpages at this point is that the loader is shown constantly. We only want it to appear when we are in the middle of loading our content. We can hide the loader once our webpage is ready by using the following code:

1
$(document).ready(function () {
2
    $(".loader").fadeOut();
3
});

Since we want to control what happens when a user clicks on any of the links in our navigation menu, we need to attach a listener to those links. The handler function for the listener will contain all the code that we want to execute on each link click. Here is the code for our click handler:

1
$("nav li a").on("click", function(event) {
2
    event.preventDefault();
3
    
4
    const loadURL = `${$(this).attr("href")} #content`;
5
    $("#content").hide("fast", function() {
6
      loadContent(loadURL);
7
    });   
8
    $(".loader").fadeIn("normal");
9
    
10
    window.location.hash = $(this).attr("href").slice(0, -5);
11
});

The first thing that we do inside the click handler is prevent the default action from taking place. The default action in this case refers to the user navigating to the linked URL.

Since we have prevented the linked URL from loading in the browser, it becomes our responsibility to load this content manually for viewers. We do this by first getting the value of the href attribute for the clicked link. We also append #content at the end of the URL because that's what we actually want to load. 

We use the hide() method in jQuery to hide our #content section. We are hiding this section because it currently contains the markup for the page from which users are trying to navigate away. The hide() method accepts a string or number as its first parameter. This value determines how long it takes to hide the selected element. Setting it to fast hides the content in 200ms.

The hide() method animates the width, height, and opacity of the selected element till they go to 0. The display property is set to none once they reach zero.

The second parameter is a callback function that fires once the hiding animation is complete. We make a call to loadContent() inside the callback function.

Next, we use the fadeIn() method to make our loader element visible while we load the page content. We also update the URL of the page to add a hash value that reflects the currently clicked link.

Now, we will define our loadContent() function, which accepts a URL that you want to load as its parameter. The loadContent() function uses another helper function called showNewContent() as shown below:

1
function loadContent(url) {
2
    $("#content").load(url, function() {
3
      showNewContent();
4
    });
5
}
6
7
function showNewContent() {
8
    $("#content").show("fast", function() {
9
      $(".loader").fadeOut("fast");
10
    });
11
}

The loadContent() method uses the built-in load() method in jQuery to load the content of a specified URL in our #content element. The callback function executes once the loading is complete.

We use the callback function to execute another function called showNewContent(). Remember when I used the hide() method to hide the #content element? We will now make it visible again with the help of the show() method.

The show() method is basically the opposite of the hide() method. It will make the selected elements visible by gradually increasing their width, height, and opacity.

In the previous section, I used some CSS to make sure that the width of our content element always stays at 100%. This was done to counteract the effect of show() and hide() updating the width of the selected element. Keeping the width constant while animating the height and opacity looks better in my opinion.

Final Thoughts

In this tutorial, we learned how to use built-in methods in the popular jQuery library to load in and animate the content of different webpages on our website.

There are a few things to keep in mind if you want to recreate the effect on your website. First, the markup should have a content element where you will dynamically load new content with the help of AJAX requests. Second, the click handler for all the links should prevent the default behavior of navigating to the clicked link. Third, the webpages you are trying to load this way should ideally be part of the same domain, subdomain, etc. This is because they will be subject to the same-origin policy.

It is also possible to achieve the same effect using pure JavaScript if you aren't intent on using jQuery.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.