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?