jQuery 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/imghw/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>
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:
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.
Handling link clicks and content loading
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: <

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

目录1:basename()2:copy()3:dirname()4:disk_free_space()5:disk_total_space()6:file_exists()7:file_get_contents()8:file_put_contents()9:filesize()10:filetype()11:glob()12:is_dir()13:is_writable()14:mkdir()15:move_uploaded_file()16:parse_ini_file()17:
