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:
xxxxxxxxxx
1
var image = document.querySelector('#image');
2
3
image.onclick = function() {
4
image.src = 'https://dirask.com/static/bucket/1633375165831-yjQ7G6WQeL--image.png';
5
};
or:
xxxxxxxxxx
1
var image = document.querySelector('#image');
2
3
image.addEventListener('click', function() {
4
image.src = 'https://dirask.com/static/bucket/1633375165831-yjQ7G6WQeL--image.png';
5
});
In this section, we present practical example that changes image src
when you click the image.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div>Click the image:</div>
5
<br /><br />
6
<img src="https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png" onclick="changeImage(this)" />
7
<script>
8
9
function changeImage(image) {
10
image.src = 'https://dirask.com/static/bucket/1633375165831-yjQ7G6WQeL--image.png';
11
}
12
13
</script>
14
</body>
15
</html>
In this section, we present practical example that changes image src
when you click the button.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<button onclick="changeImage()">Click me</button>
5
<br /><br />
6
<img id="image" src="https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png" />
7
<script>
8
9
var image = document.querySelector('#image');
10
11
function changeImage() {
12
image.src = 'https://dirask.com/static/bucket/1633375165831-yjQ7G6WQeL--image.png';
13
}
14
15
/*
16
// OR:
17
18
image.addEventListener('click', function() {
19
image.src = 'https://dirask.com/static/bucket/1633375165831-yjQ7G6WQeL--image.png';
20
});
21
*/
22
23
</script>
24
</body>
25
</html>
Note: check this article to know more about methods of how to add an
onclick
event to the HTML element.