Home > Net >  How do I implement a toggle effect for a button using regular JS?
How do I implement a toggle effect for a button using regular JS?

Time:10-24

I'm trying to implement a kind of toggle effect with a button, when clicked it will flip between 2 images. I can get it to change once using the eventListeners on btn2 and btn3 but when I try to implement the 'toggle' effect in btn1 nothing happens when the button is clicked. Could someone tell me where I am going wrong?

<!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"></script>
        <script>
             document.addEventListener('DOMContentLoaded', function(){
                let eng = document.querySelector("#eimg");
                let spn = document.querySelector("#simg");
                let can = document.querySelector("#cimg");
                let btn1 = document.querySelector("#eswitch");
                let btn2 = document.querySelector("#sswitch");
                let btn3 = document.querySelector("#cswitch");
                btn1.addEventListener('click', function(){
                  if (eng.src == "./England.jpeg"){
                    eng.src = './England2.jpeg';
                  }else {
                    eng.src = './England.jpeg';
                  }

                })
                btn2.addEventListener('click', function(){
                    spn.src = 'Spain2.jpg';
                })
                btn3.addEventListener('click', function(){
                    can.src = 'Canada2.png';
                })
             })
        </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>
                    <div  style="width: 18rem;">
                        <img id="simg" src="./Spain.png"  alt="Silhouette of Spain">
                        <div >
                          <h5 >Spain</h5>
                          <button id="sswitch" >Spain</button>
                        </div>
                    </div>
                    <div  style="width: 18rem;">
                        <img id="cimg" src="./Canada.png"  alt="Silhouette of Canada">
                        <div >
                          <h5 >Canada</h5>
                          <button id="cswitch" >Canada</button>
                        </div>
                    </div>
    </body>
</html>

CodePudding user response:

The problem occurs when you compare eng.src == "./England.jpeg". The eng.src property of the image is not ./England.jpeg but file:///.../England.jpeg because it's the absolute path to the image. So the conditional is false. To fix it instead of eng.src == "./England.jpeg" it should be eng.src.endsWith("/England.jpeg").

The new code:

<!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"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            let eng = document.querySelector("#eimg");
            let spn = document.querySelector("#simg");
            let can = document.querySelector("#cimg");
            let btn1 = document.querySelector("#eswitch");
            let btn2 = document.querySelector("#sswitch");
            let btn3 = document.querySelector("#cswitch");
            btn1.addEventListener('click', function () {
                if (eng.src.endsWith('England.jpeg')) {
                    eng.src = './England2.jpeg';
                } else {
                    eng.src = './England.jpeg';
                }

            })
            btn2.addEventListener('click', function () {
                spn.src = 'Spain2.jpg';
            })
            btn3.addEventListener('click', function () {
                can.src = 'Canada2.png';
            })
        })
    </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>
        <div  style="width: 18rem;">
            <img id="simg" src="./Spain.png"  alt="Silhouette of Spain">
            <div >
                <h5 >Spain</h5>
                <button id="sswitch" >Spain</button>
            </div>
        </div>
        <div  style="width: 18rem;">
            <img id="cimg" src="./Canada.png"  alt="Silhouette of Canada">
            <div >
                <h5 >Canada</h5>
                <button id="cswitch" >Canada</button>
            </div>
        </div>
</body>

</html>

CodePudding user response:

Your problem is (eng.src == "./England.jpeg") in your conditional statement:

if (eng.src == "./England.jpeg"){
    eng.src = './England2.jpeg';
} else {
    eng.src = './England.jpeg';
}

eng.src returns "http://127.0.0.1:5500/England.jpeg" not "./England.jpeg".

So (eng.src == "./England.jpeg") will always be false.

Solution is to use eng.getAttribute("src") instead;

if (eng.getAttribute("src") == "./England.jpeg"){
   eng.src = './England2.jpeg';
} else {
   eng.src = './England.jpeg';
}

CodePudding user response:

Im not really sure whats wrong as it works fine when I change the images to different images. The problem must be either a typo somewhere or they are not pointing to the right spot.

However, this code below provides you an alternate option in a more direct way IMO.Using if/else is not really needed here. You basically just want to know, is this photo src the current src yes or no?

btn1.addEventListener('click', ()=> {
              eng.src === "/England.jpeg"? // is this true or false?
              eng.src = "/England2.jpeg":  // <<< If true, do that
              eng.src = "/England.jpeg" // <<< If false, do that
             
            })

Everyones a bit different, but if my question is yes or no and I only need one thing to happen either way based off the answer... I choose ternary operator over if/else. You also need to use it ALL the time in React if you ever get into React one day.

  • Related