Thursday, 13 May 2021

Change image source on click on image using JQuery.

 It is also very simple using .attr() method to change any image source on click.

// Change src attribute of image

       $(this).attr("src", "2.jpeg");

This will change first image with 2.jpeg.

Complete example-

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

    $("img").click(function(){

        // Change src attribute of image

        $(this).attr("src", "2.jpeg");

    });    

});

</script>

</head>

<body>

      <img src="1.jpg" alt="image"></img>

        <p><strong>Instruction:</strong> Click on the image to change its source.</p>

</body>

</html>

No comments:

Post a Comment

Change image source dynamically on hyperlink

 Changing image source dynamically using JQuery. Here in this example I have created there hyperlink and stored all images in the same folde...