JavaScript- Set an Image Source Dynamically Using JS

Last Updated : 19 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

These are the following ways to change the given image dynamically:

1. Using src Property of JS

The approach behind this code is to allow the user to change an image dynamically when they click a button. Upon clicking the "Change Image" button, the 'changeImage' function is triggered, which updates the 'src' attribute of the image element to display a new image. This provides an interactive way to swap content on the page in response to user actions.

HTML
<!DOCTYPE html>
<html lang="en">
<body>
<img id="myImage" src=
"https://media.geeksforgeeks.org/wp-content/uploads/20241216161009363184/Nodejs-Design-patterns.webp" 
     alt="Initial Image">
<button onclick="changeImage()">Change Image</button>
<script>
    function changeImage() {
        // Get the image element by its ID
        let img = document.getElementById("myImage");
        // Set the new image source
        img.src = 
"https://media.geeksforgeeks.org/wp-content/uploads/20241214171552887389/Expressjs-tutorial.webp";
      // Change to a different image
    }
</script>
</body>
</html>

2. Based on Condition

The approach behind this code is to change the displayed image based on the time of day. When the page loads, the script checks the current hour. If it's before noon, it sets the image to a "nodejs-design-patterns" image; otherwise, it shows an "expressjs tutrorial" image. This dynamic behavior adjusts the content based on the system's time, offering a personalized user experience.

HTML
<!DOCTYPE html>
<html lang="en">
<body>
<img id="myImage" src=
"https://media.geeksforgeeks.org/wp-content/uploads/20241216161009363184/Nodejs-Design-patterns.webp" 
     alt="Initial Image" width="300">

<script>
    // Example: Change image based on the time of day
    window.onload = function() {
        let img = document.getElementById("myImage");

        let hour = new Date().getHours();
      // Get current hour
        if (hour < 12) {
            img.src = 
"https://media.geeksforgeeks.org/wp-content/uploads/20241216161009363184/Nodejs-Design-patterns.webp";
          // Display morning image
        } else {
            img.src =
 "https://media.geeksforgeeks.org/wp-content/uploads/20241214171552887389/Expressjs-tutorial.webp"; 
          // Display evening image
        }
    };
</script>
</body>
</html>

Next Article
Article Tags :

Similar Reads