Changing the image source using jQuery

Let's discuss, how to change the source of the image from one image to another using jQuery?
Submitted by Pratishtha Saxena, on August 26, 2022

There are various instances when there is a need to change the image when needed. This has to be dynamic as it generally depends on some click events or other events. Therefore, it can be handled by jQuery. There can be different situations when the image needs to be swapped with a different one to meet the requirement. Over here, we'll be discussing how to perform this task with a click of a button using jQuery.

This thing can be achieved by again using one of the most important methods of jQuery, i.e., the .attr() method. It is a very useful method, which helps either to set or return the attributes of the selected element.

Syntax:

Different attributes can be specified over here and set them. Since we need to change the source of the image, the attribute we need to specify here is the src. The address of the new image that has to be swapped with the old one is given in the src (source) attribute.

Let's take a look at the following given example.

Example to change the image source using jQuery

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2>Change The Img Source On Click Using jQuery</h2>
    <p>When the following button is clicked, the image gets changed.</p>
    <img id="myImg" src="https://media.istockphoto.com/photos/mountain-landscape-picture-id517188688?k=20&m=517188688&s=612x612&w=0&h=i38qBm2P-6V4vZVEaMy_TaTEaoCMkYhvLCysE7yJQ5Q=">
    <br><br>
    <button type="button" id="button1">Get Flower Img</button>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('#button1').on('click',function(){
            $('#myImg').attr('src','https://cdn.pixabay.com/photo/2015/04/19/08/32/marguerite-729510__480.jpg');
        })
    });
  </script>
</html>

Output:

Example: Changing the image source





All jQuery Examples

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.