How to Change the Image Source Using jQuery

As a web developer, you may have come across a situation where you need to change the source of an image dynamically based on some user interaction or based on some conditions.

One of the easiest ways to accomplish this task is by using jQuery.

In this tutorial, we’ll show you how to change the source of an image using jQuery.


What is jQuery?

jQuery is a fast, small, and feature-rich JavaScript library that makes HTML document traversal and manipulation, event handling, and animation much simpler with an easy-to-use API that works across a multitude of browsers.

With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.

How to Change the Image Source Using jQuery?

To change the source of an image, you need to find the image element and then modify its “src” attribute. Here is the code to do that:

$(document).ready(function() {
    $("#changeImage").click(function() {
        $("#image").attr("src", "newImage.jpg");
    });
});

In this example, we are changing the source of an image with an id “image” when a button with id “changeImage” is clicked.

When the button is clicked, the “src” attribute of the image is updated to “newImage.jpg”.

You can also change the source of an image using the following code:

$("#image").attr("src", function(index, attr) {
    return attr === "oldImage.jpg" ? "newImage.jpg" : "oldImage.jpg";
});

This code updates the source of the image based on its current source.

If the source of the image is “oldImage.jpg”, then it changes it to “newImage.jpg”, and if it’s “newImage.jpg”, then it changes it to “oldImage.jpg”.


Conclusion

In this tutorial, we have shown you how to change the source of an image using jQuery.

By using jQuery, you can easily change the source of an image based on some user interaction or based on some conditions.

If you have any questions or if you want to learn more about jQuery, feel free to leave a comment below.