Home > Mobile >  changing a Javascript image on event listener click
changing a Javascript image on event listener click

Time:03-18

i have a Div holding an image with the id sunset that i want to add an onclick to to change its width from the CSS 25% to 100%

cannot see why my code is not working

var content = document.getElementById("sunset");
var first_click = true;

content.addEventListener("click", function () {
    if (first_click) {
        content.style.width = "100%";
    }

    else {
        content.style.width = "25%";
    }

});

CSS

#sunset{
    width:25%
}

CodePudding user response:

The first if statement doesn't check if the first_click var is true (assuming that is what you intend to do). Since it is empty it would return false and the else statement would run, keeping your image at 25%.

try this:

var content = document.getElementById("sunset");
var first_click = true;

content.addEventListener("click", function () {
    if (first_click == true) {
        content.style.width = "100%";
    }

    else {
        content.style.width = "25%";
    }

});

CodePudding user response:

Have you tried adding height to your container ? This should work

var content = document.getElementById("sunset");
var first_click = true;

content.addEventListener("click", function () {

    if (first_click) {
        content.style.width = "100%";
     
        first_click = false;
    }

    else {
        content.style.width = "25%";
    }

});
#sunset{
  width:25%;
  background: #000;
  height: 200px;
}
<div id="sunset"></div> 

CodePudding user response:

The problem is that you're not toggling the first_click variable to true or false when the image is clicked. The code below fixes this by setting first_click = !first_click:

var content = document.getElementById("sunset");
var first_click = true;
content.addEventListener("click", function() {
  if (first_click) {
    content.style.width = "100%";
  } else {
    content.style.width = "25%";
  }
  first_click = !first_click;
});
#sunset {
  width: 25%
}
<img id="sunset" src="https://dummyimage.com/150/f8f">

  • Related