jQuery Examples

jQuery simplifies the process of building dynamic and interactive web applications. From DOM manipulation to AJAX calls, jQuery provides a wide range of methods and techniques that are easy to implement.

In this article by The Coding College, we’ll showcase real-world jQuery examples to demonstrate its versatility and power.

1. Basic jQuery Examples

Select and Style Elements

// Change the color of all paragraphs
$("p").css("color", "blue");

Hide and Show Elements

$("#hideButton").click(function() {
    $("div").hide();
});
$("#showButton").click(function() {
    $("div").show();
});

Toggle Class

$("button").click(function() {
    $("p").toggleClass("highlight");
});

2. DOM Manipulation

Add New Elements

$("#addButton").click(function() {
    $("ul").append("<li>New Item</li>");
});

Remove Elements

$("#removeButton").click(function() {
    $("li:last").remove();
});

Get and Set Content

// Get content of the first paragraph
console.log($("p:first").text());

// Set content of all paragraphs
$("p").text("This is new content!");

3. Event Handling

Click Event

$("button").click(function() {
    alert("Button clicked!");
});

Hover Effect

$("div").hover(
    function() {
        $(this).css("background-color", "yellow");
    },
    function() {
        $(this).css("background-color", "white");
    }
);

Form Submit Event

$("form").submit(function(e) {
    e.preventDefault();
    alert("Form submitted!");
});

4. Effects and Animations

Fade Effects

$("#fadeInButton").click(function() {
    $("#box").fadeIn();
});
$("#fadeOutButton").click(function() {
    $("#box").fadeOut();
});

Slide Effects

$("#slideUpButton").click(function() {
    $("#panel").slideUp();
});
$("#slideDownButton").click(function() {
    $("#panel").slideDown();
});

Custom Animation

$("#animateButton").click(function() {
    $("#box").animate({
        left: "+=50px",
        opacity: 0.5
    }, 1000);
});

5. AJAX Examples

Load Content with AJAX

$("#loadButton").click(function() {
    $("#content").load("https://jsonplaceholder.typicode.com/posts/1");
});

Fetch Data with get()

$.get("https://jsonplaceholder.typicode.com/users", function(data) {
    console.log(data);
});

Submit Data with post()

$.post("https://jsonplaceholder.typicode.com/posts", {
    title: "jQuery Example",
    body: "Learning jQuery is fun!",
    userId: 1
}, function(response) {
    console.log("Post created:", response);
});

6. Form Validation

Check Required Fields

$("form").submit(function(e) {
    if ($("#name").val() === "") {
        alert("Name is required!");
        e.preventDefault();
    }
});

Email Validation

$("form").submit(function(e) {
    const email = $("#email").val();
    const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!regex.test(email)) {
        alert("Please enter a valid email!");
        e.preventDefault();
    }
});

7. Advanced Use Cases

Chaining Methods

$("p")
    .css("color", "red")
    .slideUp(2000)
    .slideDown(2000);

Toggle Between Two States

$("#toggleButton").click(function() {
    $("#box").toggleClass("active");
});

Real-Time Search Filter

$("#searchInput").on("keyup", function() {
    const value = $(this).val().toLowerCase();
    $("ul li").filter(function() {
        $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
    });
});

Complete Example

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Examples</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .highlight { color: red; }
        #box { width: 100px; height: 100px; background: blue; position: relative; }
    </style>
</head>
<body>
    <button id="toggleButton">Toggle Box</button>
    <div id="box"></div>
    <ul>
        <li>Apple</li>
        <li>Banana</li>
        <li>Cherry</li>
    </ul>
    <input type="text" id="searchInput" placeholder="Search...">
    <div id="panel">This is a panel</div>
</body>
</html>

JavaScript

$(document).ready(function() {
    $("#toggleButton").click(function() {
        $("#box").toggle();
    });

    $("#searchInput").on("keyup", function() {
        const value = $(this).val().toLowerCase();
        $("ul li").filter(function() {
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
        });
    });
});

Conclusion

The versatility of jQuery makes it an essential tool for web developers. From basic DOM manipulation to advanced AJAX functionality, its methods simplify complex tasks.

Leave a Comment