Share
Explore

3 advanced jQuery detailed code example

Here are three advanced jQuery code examples that demonstrate various techniques and functionalities.

Example 1: Infinite Scrolling

This code demonstrates how to implement infinite scrolling functionality, where content is loaded automatically when the user scrolls to the bottom of the page.
$(document).ready(function () {
var pageNum = 1;

function loadMoreContent() {
$.ajax({
url: "loadMoreContent.php",
type: "GET",
data: { page: pageNum },
success: function (data) {
if (data) {
$("#contentContainer").append(data);
pageNum++;
} else {
$(window).off("scroll", checkScroll);
}
},
});
}

function checkScroll() {
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
loadMoreContent();
}
}

$(window).on("scroll", checkScroll);
});

The html file which will call Example 1: Infinite Scrolling javascript file
Here is the HTML file that will call the Infinite Scrolling JavaScript file (Example 1) you mentioned. First, make sure you have the jQuery library included and reference the infinite scrolling script, which we'll name infiniteScroll.js.
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Infinite Scrolling Example</title>
<style>
.post {
margin-bottom: 20px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
</style>
</head>
<body>
<div id="content-wrapper">
<div class="post">Post 1</div>
<div class="post">Post 2</div>
<div class="post">Post 3</div>
<!-- More posts go here -->
</div>
<div id="loading" style="display: none;">
<span>Loading...</span>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="infiniteScroll.js"></script>
</body>
</html>
The infinite scrolling script (infiniteScroll.js) should be placed in a separate file. Here's the script file you can use for this example:
infiniteScroll.js:

$(document).ready(function () {
let isLoading = false;

$(window).scroll(function () {
if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
if (!isLoading) {
isLoading = true;
$('#loading').show();

setTimeout(function () {
let newPost = $('<div class="post"></div>');
newPost.text('New post loaded');
$('#content-wrapper').append(newPost);

isLoading = false;
$('#loading').hide();
}, 1000);
}
}
});
});
In this example, the JavaScript file infiniteScroll.js is loaded after the jQuery library in the HTML file. The script checks if the user has scrolled near the bottom of the page and if so, it appends a new post. The isLoading variable prevents multiple requests from being made at once.
what is the source of data that provides content in this infinite scroll?

The source of data that provides content in the infinite scroll can be any server-side API or a data source, like a database, that returns the required content in a format such as JSON or XML[3]. When implementing AJAX-enabled infinite scrolling, you would specify the data source URL in the plugin's options. The plugin then sends AJAX requests to fetch the data from the specified source and dynamically loads it onto your document as the user scrolls or clicks the Load More button[3]. This enables seamless and efficient loading of content without requiring a full page refresh.
References:
[1]

In this specific example what is the source of data:

In this specific example, the source of data is an API that returns quotes [1]. The infinite scrolling JavaScript will send AJAX requests to this API to fetch the data in a format like JSON or XML. As the user scrolls down the page or clicks the "Load More" button, the plugin will dynamically load and display the quotes from the API, providing a seamless and efficient content-loading experience without requiring a full page refresh [2].
References:
[3]

The code which does that


Here's a simple example using JavaScript, jQuery, and a public API to implement infinite scrolling. In this example, we'll use the Quotes API () to fetch quotes and display them as the user scrolls.
First, include jQuery in your HTML file:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Infinite Scroll Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="quotes-container"></div>
</body>
</html>

Add the following JavaScript/jQuery code to implement the infinite scrolling functionality:

$(document).ready(function() {
const quotesAPI = "https://type.fit/api/quotes";
let currentIndex = 0;
const quotesPerLoad = 10;

function loadMoreQuotes() {
$.getJSON(quotesAPI, function(data) {
let quotesHTML = "";
for (let i = currentIndex; i < currentIndex + quotesPerLoad; i++) {
if (!data[i]) {
break;
}
quotesHTML += `<p><strong>Quote ${i + 1}:</strong> ${data[i].text} - <em>${data[i].author || "Unknown"}</em></p>`;
}
currentIndex += quotesPerLoad;
$("#quotes-container").append(quotesHTML);
});
}

loadMoreQuotes();

$(window).scroll(function() {
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 50) {
loadMoreQuotes();
}
});
});
This code fetches 10 quotes at a time from the Quotes API and appends them to the #quotes-container div. As the user scrolls to the bottom of the page, the loadMoreQuotes function is called again to fetch and display more quotes.

Example 2: Animated Accordion
This code example demonstrates how to create an animated accordion using jQuery's slideDown, slideUp, and siblings methods.
javascript
Copy code
$(document).ready(function () {
$(".accordion-header").on("click", function () {
var content = $(this).next(".accordion-content");

if (content.is(":visible")) {
content.slideUp(300);
} else {
content.slideDown(300);
content.siblings(".accordion-content:visible").slideUp(300);
}
});
});
Example 3: AJAX Form Submission
This code example demonstrates how to submit a form using AJAX, displaying a success or error message based on the server's response.
javascript
Copy code
$(document).ready(function () {
$("#myForm").on("submit", function (event) {
event.preventDefault();
var formData = $(this).serialize();

$.ajax({
url: "submitForm.php",
type: "POST",
data: formData,
success: function (data) {
if (data === "success") {
$("#formStatus").html("Form submitted successfully!").css("color", "green");
$("#myForm")[0].reset();
} else {
$("#formStatus").html("Error submitting form!").css("color", "red");
}
},
error: function (jqXHR, textStatus, errorThrown) {
$("#formStatus").html("Error submitting form!").css("color", "red");
},
});
});
});
These examples demonstrate advanced jQuery techniques, such as infinite scrolling, animated accordions, and AJAX form submissions.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.