Home > OS >  How can I change the source of an image so that when a button is clicked?
How can I change the source of an image so that when a button is clicked?

Time:10-24

I am trying to have an image swap with another when a user clicks a button on a webpage. Looking less for an answer and more for why the logic I am trying isn't working or what I am missing. Trying to solve with plain JS to get to grips with the language. Here is what I am trying:

<!DOCTYPE html>

<html lang="en">
    <head>
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP JcXn/tWtIaxVXM" crossorigin="anonymous">
             document.addEventListener('DOMContentLoaded', function(){
                let eng = document.querySelector("#eimg");
                let btn1 = document.querySelector("#eswitch");
                btn1.addEventListener('click', function(){
                    eng.src = 'England2.jpeg';
                })
             })
        </script>
        <link href="styles.css" rel="stylesheet">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>My Webpage</title>
    </head>
    <body>
        <div >
            <h1 >Travel</h1>
        </div>
        <div>
          <nav aria-label="breadcrumb">
            <ol >
              <li ><a href="./index.html">Home</a></li>
              <li  aria-current="page">Travel</li>
            </ol>
          </nav>
                <div  style="width: 18rem;">
                    <img id="eimg" src="./England.jpeg"  alt="Silhouette of England">
                    <div >
                      <h5 >England</h5>
                      <button id="eswitch" >England</button>
                      </div>
                    </div>

    </body>
</html>

CodePudding user response:

You will need to break out your JS into its own script block.

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP JcXn/tWtIaxVXM" crossorigin="anonymous">
</script>
<script>
    document.addEventListener('DOMContentLoaded', function(){
        let eng = document.querySelector("#eimg");
        let btn1 = document.querySelector("#eswitch");
        btn1.addEventListener('click', function(){
            eng.src = 'England2.jpeg';
                console.log(eng)
            })
        })
</script>
  • Related