0

I want to create a simple toggle image control which changes it's image when checked or unchecked. I tried to create a seperate class for it because I intend to add a listener to react to changes of the toggle state and it seemed like a good solution to me. The number of toggleImages will depend on the user so I tried creating them using js.

<html>
  <head>

    
  </head>
  <body>

    <div id="box">

    </div>

  </body>
  <script>
      class ToogleImage{
        constructor(imgToggled, imgNotToggled, img){
          this.toggled = false;
          this.imgToggled = imgToggled;
          this.imgNotToggled = imgNotToggled;
          this.img = img;
          this.refreshImage();
          this.img.addEventListener('click', function (e) {
            this.toggleState();
            this.refreshImage();
          });
        }
           toggleState(){
            this.toggled!=this.toggled();
          }
           refreshImage(){
            if(this.toggled){
              img.setAttribute('src', this.imgToggled);

            }else{
              img.setAttribute('src', this.imgNotToggled);
            }
          }

      }

      var img = document.createElement("img");
      var toggleImage = new ToogleImage("https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded", "https://www.stackoverflowbusiness.com/hubfs/B2B-SO/images/SO_Talent.svg?t=1515694040462", img);
      document.getElementById('box').appendChild(img)
    </script>

</html>

Problem is that the image will not display. Does anyone know how to fix this?

Curunir
  • 1,186
  • 2
  • 13
  • 30
  • The image displays when I run that code. Clicking on the image throws an error… but the image is still displayed when that happens. – Quentin Jan 14 '18 at 09:44
  • did you change edit your question? it now works for some reason – CoderPi Jan 14 '18 at 09:45
  • Sorry I meant that the second toggle image will not show up, my bad. – Curunir Jan 14 '18 at 09:45
  • @Curunir — You should do some basic debugging. You could at least quote the error message you get when you click the image. – Quentin Jan 14 '18 at 09:46
  • @Quentin "test.html:23 Uncaught TypeError: this.toggleState is not a function at HTMLImageElement. (test.html:23)" – Curunir Jan 14 '18 at 09:47
  • 1
    In `toggleState()` remove the parenthesis (and I would personally write the `!=` as `= !`): `this.toggled= !this.toggled;` – rolfv1 Jan 14 '18 at 09:48
  • Oh god, thats embarassing. I am sorry for that ridiculous question – Curunir Jan 14 '18 at 12:37

0 Answers0