Languages
[Edit]
EN

JavaScript - change image on click

3 points
Created by:
Leen-Kerr
571

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.

 

References

  1. HTMLImageElement.src - Web APIs | MDN
  2. <img>: The Image Embed element - HTML: HyperText Markup Language | MDN

Alternative titles

  1. JavaScript - change image src onclick()
  2. JavaScript - change image url on click event
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join