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>
<div>
    <img src='images/berry.jpg' id='myImg'>
</div>

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

Example:

const img = document.getElementById('myImg');
let currentImgIdx = 1;
const images = [ 
    'images/berry.jpg',
    'images/cat.jpg',
    'images/bridge.jpg',
    'images/coffee.jpg',
    'images/leaves.jpg',
    'images/lock.jpg'
]; 

// 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];
    currentImgIdx++;
    // Increment current image idx by 1
}

Thanks for reading.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts