In this tutorial we will learn How To Change Image OnClick using jQuery. For this we can use jQuery attr() Method which changes the value of src attribute of img tag.
Table of Contents
jQuery attr() Method
jQuery attr() Method sets or returns the value of the HTML attributes of HTML tags.
HTML Code
HTML Code is given below, in this code we have a image tag and a button tag.
<!DOCTYPE html>
<html lang="en">
<head>
<title>How To Change Image OnClick using jQuery</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
<img src="samsung.png" id="img" style="width:200px;">
<br><br>
<button>Click Me!</button>
<script>
$("button").click(function(){
$("#img").attr("src", "apple.png");
});
</script>
</body>
</html>
JQuery Code
JQuery Code is given below.
$('#img') is an id selector used to select the img tag.
Then attr() method will change the src attribute value. This will change the image on the web page.
This is done on click of a button using click() method.
<script>
$("button").click(function(){
$("#img").attr("src", "apple.png");
});
</script>
Video Tutorial
Watch video tutorial on How To change image using jQuery.