EN
JavaScript - change image on click
3
points
In this article, we would like to show you how to change the image src on click event using JavaScript.
Quick solution:
var image = document.querySelector('#image');
image.onclick = function() {
image.src = 'https://dirask.com/static/bucket/1633375165831-yjQ7G6WQeL--image.png';
};
or:
var image = document.querySelector('#image');
image.addEventListener('click', function() {
image.src = 'https://dirask.com/static/bucket/1633375165831-yjQ7G6WQeL--image.png';
});
Practical examples
1. by clicking on image
In this section, we present practical example that changes image src
when you click the image.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<div>Click the image:</div>
<br /><br />
<img src="https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png" onclick="changeImage(this)" />
<script>
function changeImage(image) {
image.src = 'https://dirask.com/static/bucket/1633375165831-yjQ7G6WQeL--image.png';
}
</script>
</body>
</html>
2. by clicking on button
In this section, we present practical example that changes image src
when you click the button.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<button onclick="changeImage()">Click me</button>
<br /><br />
<img id="image" src="https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png" />
<script>
var image = document.querySelector('#image');
function changeImage() {
image.src = 'https://dirask.com/static/bucket/1633375165831-yjQ7G6WQeL--image.png';
}
/*
// OR:
image.addEventListener('click', function() {
image.src = 'https://dirask.com/static/bucket/1633375165831-yjQ7G6WQeL--image.png';
});
*/
</script>
</body>
</html>
Note: check this article to know more about methods of how to add an
onclick
event to the HTML element.