Home > Web Front-end > JS Tutorial > body text

jQuery Tutorial: How to load and animate content using jQuery

王林
Release: 2023-09-03 21:21:07
Original
1298 people have browsed it

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.




    
    
    
    Home
    

jQuery Tutorial: How to load and animate content using jQuery

Embrace Pawsitivity, Transform Lives!

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

Our animal Welfare NGO provides a range of services to support animal welfare:

  1. Rescue and rehabilitation of abused and abandoned animals
  2. Adoption programs to find loving homes for animals in need
  3. Education and awareness campaigns to promote responsible pet ownership
  4. Lobbying and advocacy for stronger animal protection laws
  5. Collaboration with local communities to implement spay/neuter programs
Copy after login
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);
   }
 }
Copy after login

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;
}
Copy after login

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();
});
Copy after login

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);
});
Copy after login

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");
    });
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!