How to Change an Image on Button Click in JavaScript?

If you want to change an image dynamically on a button click or any other such event, you can take the help of the src attribute. The src attribute basically specifies the URL of the image that is to be shown.

So if we change the value of the src attribute from JavaScript dynamically, it will automatically change the image.

Below is the HTML code for it:

<button onclick='changeImage()'>Change Image</button>
    <img src='images/berry.jpg' id='myImg'>

And here is the full JavaScript code with a live example:


const img = document.getElementById('myImg');
let currentImgIdx = 1;
const images = [ 

// Call changeImage() function on button click
function changeImage(){
    if(currentImgIdx >= images.length){
        currentImgIdx = 0;
        // If current idx exceeds images array
        // length, reset it to 0 again
    img.src = images[currentImgIdx];
    // Increment current image idx by 1

Thanks for reading.