Script does not work although the logic is fine

2

What I'm trying to do is that the div is painted red on the first click and the second click is aqua but does not work. For me the script is fine but I do not know what happens

var div;
var coloreado = 0;;

function clickdiv() {
  div = document.getElementsByClassName("divcolor");
  div[0].addEventListener("click", darcolor, false);
}

function darcolor() {

  if (coloreado == 0) {
    div[0].style.backgroundColor = "red";
    coloreado = 1;
  }
  if (coloreado == 1) {
    div[0].style.backgroundColor = "aqua";
    coloreado = 0;
  }

}

window.onload = clickdiv;
.divcolor {
  height: 100px;
  width: 100px;
  background-color: aqua
}
<div class="divcolor">

</div>
    
asked by Orlando Pasaca Rojas 06.03.2018 в 04:16
source

3 answers

5

There is a small logic error, and it is that the comparison of coloreado is executed with 0, which is true, but in said result (after entering the if) the variable is set to 1 and therefore it is the next condition is true and the content of the second if is also executed.

An else if solves it, although there are other ways:

var div;
var coloreado = 0;

function clickdiv() {
  div = document.getElementsByClassName("divcolor");
  div[0].addEventListener("click", darcolor, false);
}

function darcolor() {
  if (coloreado == 0) {
    div[0].style.backgroundColor = "red";
    coloreado = 1;
  } else if (coloreado == 1) {
    div[0].style.backgroundColor = "aqua";
    coloreado = 0;
  }

}

window.onload = clickdiv;
.divcolor {
  height: 100px;
  width: 100px;
  background-color: aqua
}
<div class="divcolor">

</div>
    
answered by 06.03.2018 / 04:46
source
0

Change the second if for an else

if (coloreado == 0) {
        div[0].style.backgroundColor = "red";
        coloreado = 1;
        console.log("Hola soy rojo");
    }
    else {
        div[0].style.backgroundColor = "aqua";
        coloreado = 0;
        console.log("Hola soy aqua");
    }
    
answered by 06.03.2018 в 04:45
0

Greetings is only in the logic of the comparison, at some point it should go through a secondary condition ie an else:

  var div;
var coloreado = 0;;

function clickdiv() {
  div = document.getElementsByClassName("divcolor");
  div[0].addEventListener("click", darcolor, false);
}

function darcolor() {

  if (coloreado == 0) {
    div[0].style.backgroundColor = "red";
    coloreado = 1;
  }
  else{


    div[0].style.backgroundColor = "aqua";
    coloreado = 0;
  }

}

window.onload = clickdiv;

From the technical point of view, it never leaves the first if it is obviously fulfilled but there is never a case of passing to the else

    
answered by 06.03.2018 в 04:50