jQuery is a popular JavaScript library that simplifies web development tasks. It offers various features for creating interactive and dynamic web pages. Many developers use jQuery to enhance their websites and build engaging user interfaces.
Learning jQuery through practical examples can help developers improve their skills and create better web applications. By using these examples, you can learn how to apply jQuery in real-world scenarios. These examples also include the complete source code, enabling developers to examine and adapt the implementation details for their own projects.
However, before exploring the examples, let me explain how to include jQuery in a project.
To include jQuery in your project using a Content Delivery Network (CDN), you need to add a <script> tag in your HTML file that points to the jQuery library hosted on a CDN. Here’s how you can do it:
- Open your HTML file in a text editor.
- Inside the
<head>section of your HTML file, add the following line of code:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
This line includes the minified version of jQuery from the official jQuery CDN. Replace 3.6.0 with the specific version of jQuery you want to use. Alternatively, you can place the <script> tag just before the closing </body> tag in your HTML file. This is often recommended for better performance, as it allows the browser to load the HTML content before loading the JavaScript files.
- Save your HTML file.
Now, whenever a user visits your web page, their browser will download the jQuery library from the CDN and make it available for use in your JavaScript code.
Here’s an example of how your HTML file might look with jQuery included via CDN:
<!DOCTYPE html>
<html>
<head>
<title>My Web Page</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<!-- Your HTML content goes here -->
<script>
// Your JavaScript code that uses jQuery goes here
$(document).ready(function() {
// jQuery code
});
</script>
</body>
</html>
In this example, the jQuery library is included in the <head> section, and the JavaScript code that uses jQuery is placed before the closing </body> tag.
Using a CDN to include jQuery has several benefits:
- It reduces the load on your web server since the jQuery file is served from the CDN’s servers.
- It increases the likelihood that a user’s browser already has the jQuery file cached, resulting in faster loading times.
- It ensures that you are using a widely used and trusted version of the jQuery library.
However, remember that if the CDN is unavailable or the user is offline, your jQuery-dependent code may not work. In such cases, you can consider fallback options, such as hosting a local copy of the jQuery library on your server.
Now, let me show you 51 jQuery examples with the complete source code.
1. Image Carousel
Image carousels are popular jQuery elements that display a rotating set of images. They add visual interest to web pages and showcase multiple pieces of content in a compact space.
jQuery makes it easy to create image carousels with smooth transitions and interactive controls. Developers can customize the carousel’s appearance, speed, and behavior to fit their needs.
Here’s a basic example of an image carousel using jQuery:
<div id="carousel">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
let currentIndex = 0;
const images = $('#carousel img');
function showNextImage() {
images.eq(currentIndex).fadeOut(500);
currentIndex = (currentIndex + 1) % images.length;
images.eq(currentIndex).fadeIn(500);
}
setInterval(showNextImage, 3000);
});
</script>
This code creates a simple carousel that fades between images every 3 seconds. The jQuery script handles the image transitions and loops through the available images.
Developers can enhance this basic carousel by adding navigation buttons, touch swipe support, or auto-play features. Many jQuery plugins also offer pre-built carousels with advanced functionality.
Image carousels work well for showcasing product photos, testimonials, or featured content. They can help save webpage space while presenting multiple images to users.
Check out JavaScript Examples [51 Useful Examples]
2. Form Validation
jQuery form validation helps ensure users enter correct information before submitting forms. It checks input fields and displays error messages for invalid data.
To implement form validation with jQuery, include the jQuery library and validation plugin in your HTML file.
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
Next, create a form with input fields and a submit button.
<form id="myForm">
<input type="text" name="name" required>
<input type="email" name="email" required>
<button type="submit">Submit</button>
</form>
Now, add jQuery code to validate the form:
$(document).ready(function() {
$("#myForm").validate({
rules: {
name: "required",
email: {
required: true,
email: true
}
},
messages: {
name: "Please enter your name",
email: {
required: "Please enter your email",
email: "Please enter a valid email"
}
},
submitHandler: function(form) {
form.submit();
}
});
});
This code sets up rules for each field and defines custom error messages. The submitHandler function is called when the form passes validation.
You can also add custom validation methods for specific requirements:
$.validator.addMethod("customRule", function(value, element) {
return /^[A-Za-z]+$/.test(value);
}, "Please enter only letters");
Apply this custom rule to a field by adding it to the rules object:
rules: {
name: {
required: true,
customRule: true
}
}
jQuery form validation improves user experience by providing instant feedback. It reduces server load by catching errors before submission.
Check out How to Check Which Radio Button is Selected Using jQuery?
3. Dynamic Content Loading
jQuery makes it easy to load content dynamically without requiring a full page refresh. This technique enhances the user experience by making websites appear faster and more interactive.
One common method is using the .load() function. It fetches data from a server and puts it into a selected element. Here’s a basic example:
$('#result').load('data.html');
This code loads the contents of data.html into an element with the ID ‘result’.
For more control, developers can use the $.ajax() method. It allows customization of the request and handling of different response types. Here’s an example:
$.ajax({
url: 'data.json',
method: 'GET',
dataType: 'json',
success: function(data) {
$('#result').html(data.content);
},
error: function() {
$('#result').html('Error loading data');
}
});
This code fetches JSON data and updates the page based on the response.
Another useful technique is infinite scrolling. It loads more content as the user scrolls down. Here’s a simple implementation:
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
loadMoreContent();
}
});
function loadMoreContent() {
$.get('more-data.html', function(data) {
$('#content').append(data);
});
}
This code checks if the user has scrolled to the bottom of the page. If so, it loads more content.
Dynamic content loading enhances websites by making them more responsive and user-friendly. It reduces page load times and provides a smoother browsing experience.
Read Execute Functions After Page Load Using jQuery
4. Tooltip Implementation
Tooltips are handy UI elements that provide extra information when users hover over specific items. jQuery makes it easy to add tooltips to web pages.
To create a basic tooltip, start by adding a data attribute to the HTML element:
<button data-tooltip="Click me!">Hover over me</button>
Next, use jQuery to select elements with the data-tooltip attribute and apply the tooltip functionality:
$(document).ready(function() {
$('[data-tooltip]').hover(
function() {
var tooltip = $('<div class="tooltip"></div>');
tooltip.text($(this).data('tooltip'));
$('body').append(tooltip);
var pos = $(this).offset();
tooltip.css({
top: pos.top + $(this).height() + 5,
left: pos.left
});
tooltip.fadeIn();
},
function() {
$('.tooltip').remove();
}
);
});
This code creates a tooltip div when the user hovers over an element. It positions the tooltip below the element and removes it when the user moves away.
Add some CSS to style your tooltip:
.tooltip {
position: absolute;
background: #333;
color: #fff;
padding: 5px;
border-radius: 3px;
display: none;
}
This basic implementation can be customized to fit different design needs. You can adjust the positioning, add animations, or include more complex content in the tooltips.
For more advanced features, consider using a jQuery tooltip plugin. These plugins offer options like AJAX loading, custom styling, and advanced positioning.
Check out Handle Dropdown Change Event in jQuery
5. AJAX Pagination
AJAX pagination allows web pages to load content dynamically without refreshing the entire page. This technique improves user experience and reduces server load.
jQuery simplifies AJAX pagination implementation. It handles API requests and updates the page content smoothly.
A basic AJAX pagination setup involves a few key components. These include an HTML container for the paginated content, pagination controls, and JavaScript code to handle user interactions.
Here’s a simple example of AJAX pagination using jQuery:
<div id="content"></div>
<div id="pagination"></div>
<script>
$(document).ready(function() {
var itemsPerPage = 10;
var currentPage = 1;
function loadPage(page) {
$.ajax({
url: 'get-data.php',
data: { page: page, limit: itemsPerPage },
success: function(response) {
$('#content').html(response.data);
updatePagination(response.totalPages);
}
});
}
function updatePagination(totalPages) {
var paginationHtml = '';
for (var i = 1; i <= totalPages; i++) {
paginationHtml += '<button class="page-btn" data-page="' + i + '">' + i + '</button>';
}
$('#pagination').html(paginationHtml);
}
$(document).on('click', '.page-btn', function() {
currentPage = $(this).data('page');
loadPage(currentPage);
});
loadPage(currentPage);
});
</script>
This code sets up a content area and pagination buttons. It uses AJAX to fetch data from the server and update the page content.
The loadPage function sends a request to the server with the current page number and items per page. It then updates the content and pagination buttons based on the response.
The updatePagination function creates the page number buttons. It uses the total number of pages returned by the server.
Event listeners on the pagination buttons trigger page changes when clicked. This updates the content without a full page reload.
To complete this setup, create a server-side script (e.g., get-data.php) to handle the AJAX requests. This script should return the requested data and the total number of pages.
Read How to Check if a Checkbox is Checked Using jQuery
6. Smooth Scrolling
Smooth scrolling is a popular jQuery effect that enhances website navigation. It creates a fluid motion when users click on links that lead to different sections of a page.
To implement smooth scrolling, you’ll need jQuery and a bit of JavaScript. Here’s a basic example:
<a href="#section1">Go to Section 1</a>
<div id="section1">Section 1 content</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$('a[href^="#"]').on('click', function(event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
});
});
</script>
This code selects all links that start with a hash (#) and adds a click event listener. When clicked, it prevents the default jump and instead animates the scroll over 500 milliseconds.
You can adjust the animation speed by changing the number in the animate function. A lower number makes it faster, while a higher number slows it down.
Smooth scrolling improves user experience by making navigation feel more natural and less abrupt. It’s especially useful on long, single-page websites.
Remember to test your smooth scrolling on various devices and browsers to ensure it functions properly for all users.
Check out Call a JavaScript Function When a Checkbox is Checked or Unchecked
7. Sticky Navigation Bar
A sticky navigation bar is a useful feature that keeps the menu visible as users scroll down a webpage. This enhances site navigation and improves user experience.
To create a sticky navbar using jQuery, you’ll need HTML, CSS, and JavaScript. Start with a basic HTML structure for your navigation menu.
The CSS should style the navbar and set its position to “fixed” when it becomes sticky. Use properties like “position: sticky” and “top: 0” to achieve this effect.
Here’s a simple jQuery code snippet to make a navbar sticky:
$(window).scroll(function() {
if ($(this).scrollTop() > 100) {
$('.navbar').addClass('sticky');
} else {
$('.navbar').removeClass('sticky');
}
});
This code adds a “sticky” class to the navbar when the user scrolls more than 100 pixels down the page. The class is removed when scrolling back up.
You can customize the scroll threshold and add smooth transitions for a polished look. Test your sticky navbar on various devices to ensure it functions properly across all screen sizes.
Read Create an Expandable Table with Collapsible Rows Using HTML, CSS, and JavaScript
8. Lightbox Gallery
Lightbox galleries are popular jQuery plugins that