Search code examples
javascriptmouseoveropacity

When i mouseover the same element i want it to get darker - Vanilla JS


I want the div that i hover the mouse over that it gets darker each time i mouseover(like etch-a-sketch), but i have run into the problem of not making the opacity be able to get darker more then once.

for (var i = 0; i < (16 * 16); i++) {
  var iDiv = document.createElement('div');
  iDiv.textContent = "  ";
  iDiv.id = 'block';
  iDiv.className = 'block';
  var container = document.getElementById("container");

  container.appendChild(iDiv);

  iDiv.addEventListener("mouseover", function(event) {
    // highlight the mouseover target
    this.style.backgroundColor = "black";
    this.style.opacity += 0.2;

    // reset the color after a short delay
    setTimeout(function() {
      this.target.style.color = " ";
    }, 500);
  }, false);
}
.container {
  display: grid;
  grid-template-columns: repeat(16, 1fr);
  grid-auto-rows: repeat(16, 1fr);
  width: 95%;
  height: 95%;
  border: 1px solid black;
  margin: auto;
}

#block {
  background: white;
  padding: 12.5px;
}

#block:hover {
  background: ;
}

.color {
  background: rgba {
    0,
    0,
    0,
    0.1
  }
}
<div class="container" id="container"></div>


Solution

  • The problem is, opacity gets turned into a string, so when you add 0.2 instead of getting 0.4 you get 0.20.2.

    You need to parseFloat on it first.

    for (let i = 0; i < (16*16); i++) {
      const iDiv = document.createElement('div');
      const container = document.getElementById("container");
      iDiv.textContent = "  ";
      iDiv.id = 'block';
      iDiv.className = 'block';
    
      container.appendChild(iDiv); 
    
      iDiv.addEventListener("mouseover", function(event) {   
        // highlight the mouseover target
        this.style.backgroundColor = "black";
        this.style.opacity = (parseFloat(this.style.opacity) || 0) + 0.2;
    
        // reset the color after a short delay
        setTimeout(() => {
          this.style.backgroundColor = "none";
          this.style.opacity = 0;
        }, 5000);
      }, false);
    }
    .container {
      display: grid;
      grid-template-columns: repeat(16, 1fr);
      grid-auto-rows: repeat(16, 1fr);
      width: 95%;
      height: 95%;
      border: 1px solid black;
      margin: auto;
    }
    
    #block{
      background: white;
      padding: 12.5px;
    }
    
    #block:hover{
      background:;
    }
    
    .color{
      background: rgba{0,0,0,0.1}
    }
    <div id="container" class="container"></div>

    As a side note, for your timeout, it wouldn't work because the context of this would be lost by the time the setTimeout() was called. You need to either bind() the function or use an arrow function (like I did). I bumped the timeout to 5000 instead of 500 so you can more easily see the main focus.