search
HomeWeb Front-endJS TutorialjQuery Tutorial: How to load and animate content using jQuery

Clicking on any link on a web page will usually load the contents 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 some code to load the content of the new URL into a specific element of the current web page without reloading the entire page.

This can be achieved with a little help from JavaScript. We will use the jQuery library to do the heavy lifting related to animation and AJAX content loading.

You can also use plain JavaScript to load and animate content.

Prepare mark

We will use a very simple web page to demonstrate how the effect works. However, the principles you learn here apply to other websites as well. This is the markup for the home page of the website that we will load and animate.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <nav>
      <ul>
        <li><a href="index.html">Home</a></li>
        <li><a href="about.html">About Us</a></li>
        <li><a href="team.html">Our Team</a></li>
        <li><a href="contact.html">Contact</a></li>
      </ul>
    </nav>

    <span class="loader"></span>

    <section id="content">
        <img  src="/static/imghwm/default1.png"  data-src="dog.svg"  class="lazy" / alt="jQuery Tutorial: How to load and animate content using jQuery" >

        <h1 id="Embrace-Pawsitivity-Transform-Lives">Embrace Pawsitivity, Transform Lives!</h1>

        <p>Welcome to Pawsitive Care Foundation, a dedicated organization working towards the well-being and protection of animals.</p>

        <p>Our animal Welfare NGO provides a range of services to support animal welfare:</p>

        <ol>
            <li>Rescue and rehabilitation of abused and abandoned animals</li>
            <li>Adoption programs to find loving homes for animals in need</li>
            <li>Education and awareness campaigns to promote responsible pet ownership</li>
            <li>Lobbying and advocacy for stronger animal protection laws</li>
            <li>Collaboration with local communities to implement spay/neuter programs</li>
        </ol>
    </section>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
    <script src="load-content.js"></script>
</body>
</html>
The

tag links to the style.css file, which contains the CSS used to style all web pages. The body of the web page contains the nav element, which contains a list of links that the user can access. There is a span element and a loader class. Whenever the user clicks one of the links in the navigation, we will show and hide this loader element. The loader will indicate that the page is currently loading.

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

With the help of some CSS, our page looks like this:

jQuery Tutorial: How to load and animate content using jQuery

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

Set styles for loaders and content

We will now learn how to use CSS to animate a loader so that it spins while loading new content. This is the CSS that keeps our loader spinning.

 .loader {
   background: white;
   width: 30px;
   height: 30px;
   display: inline-block;
   position: absolute;
   right: 2rem;
   top: 1.2rem;
   animation: 0.5s infinite spin;
   border-radius: 50%;
   border-top: 5px solid black;
   border-bottom: 5px solid gray;
 }

 @keyframes spin {
   0% {
     transform: rotate(0deg);
   }
   100% {
      transform: rotate(360deg);
   }
 }

There are several points to note here. First, loaders have absolute positioning. This takes it out of the normal flow of the document so that we can place it wherever we want without interrupting the flow of other content.

We use the animation property to continuously animate the loader based on spin keyframe values, where each animation loop completes in 0.5 seconds.

Using border-radius: 50% makes our loader rounded since it has the same width and height. Using different border colors at the top and bottom is just a style preference.

We will also use the following CSS to ensure that the content we are loading covers the entire width of the body.

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

This will become important when we animate the main content.

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

If you load any webpage at this time, one thing you will notice is that the loader will keep showing up. We only want it to appear when content is loading. Once our page is ready, we can use the following code-behind loader:

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

Since we want to control what happens when the user clicks any link in the navigation menu, we need to attach a listener to these links. The listener's handler function will contain all the code we want to execute every time the link is clicked. Here is the code for our click handler:

$("nav li a").on("click", function(event) {
    event.preventDefault();
    
    const loadURL = `${$(this).attr("href")} #content`;
    $("#content").hide("fast", function() {
      loadContent(loadURL);
    });   
    $(".loader").fadeIn("normal");
    
    window.location.hash = $(this).attr("href").slice(0, -5);
});

The first thing we do in the click handler is prevent the default action from happening. The default action in this example is for the user to navigate to the linked URL.

Since we have blocked the linked URL from loading in the browser, it is our responsibility to manually load this content for the viewer. To do this, we first get the value of the href attribute of the clicked link. We also append #content to the end of the URL because that’s the content we actually want to load.

We use the hide() method in jQuery to hide the #content part. We hide this section because it currently contains the markup for the page the user is trying to leave. hide() The method accepts a string or number as its first parameter. This value determines how long it takes to hide the selected element. Set it to Fast to hide content in 200 milliseconds.

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

The second parameter is a callback function, which is triggered after the hiding animation is completed. We call loadContent() in the callback function.

接下来,我们使用 fadeIn() 方法使我们的 loader 元素在加载页面内容时可见。我们还更新页面的 URL 以添加反映当前单击的链接的哈希值。

现在,我们将定义 loadContent() 函数,该函数接受您要加载的 URL 作为其参数。 loadContent() 函数使用另一个名为 showNewContent() 的辅助函数,如下所示:

function loadContent(url) {
    $("#content").load(url, function() {
      showNewContent();
    });
}

function showNewContent() {
    $("#content").show("fast", function() {
      $(".loader").fadeOut("fast");
    });
}

loadContent() 方法使用 jQuery 中内置的 load() 方法来加载 #content 元素中指定 URL 的内容。加载完成后执行回调函数。

我们使用回调函数来执行另一个名为 showNewContent() 的函数。还记得我使用 hide() 方法来隐藏 #content 元素吗?现在,我们将借助 show() 方法使其再次可见。

show() 方法基本上与 hide() 方法相反。它将通过逐渐增加所选元素的宽度、高度和不透明度来使所选元素可见。

在上一节中,我使用了一些 CSS 来确保内容元素的宽度始终保持在 100%。这样做是为了抵消 show()hide() 更新所选元素宽度的影响。在我看来,保持宽度不变,同时对高度和不透明度进行动画处理看起来更好。

最终想法

在本教程中,我们学习了如何使用流行的 jQuery 库中的内置方法来加载我们网站上不同网页的内容并为其设置动画。

如果您想在网站上重现效果,请记住一些事项。首先,标记应该有一个内容元素,您可以在 AJAX 请求的帮助下动态加载新内容。其次,所有链接的单击处理程序应防止导航到单击的链接的默认行为。第三,您尝试以这种方式加载的网页最好属于同一域、子域等。这是因为它们将受到同源策略的约束。

如果您不打算使用 jQuery,也可以使用纯 JavaScript 实现相同的效果。

The above is the detailed content of jQuery Tutorial: How to load and animate content using jQuery. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft