Search code examples
javascripthtmlcssbrightness

Increase specific element's variable value as a result of function


Using a for loop, I created a variable number of divs, which all change their background color whenever I enter them with my mouse. The nice thing is, that each div ends up having their own color. Now I would like to add a function which would decrease the brightness of a div by 10% whenever I enter it with a mouse. Problem is, until now I've only succeeded at decreasing all of the div's background color, not the individual's background color. I am sorry for phrasing this so poorly, but would appreciate any help.

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <title>Etch-a-sketch</title>
  </head>
  <body>
    <h1>Etch-a-sketch</h1>
    <button id="start">Start</button>
    <div id="container"></div>
  </body>
  <script>


  //randomColor function is taken from http://www.devcurry.com/2010/08/generate-random-colors-using-javascript.html //
  function randomRgb() {

  col =  "rgb("
  + randomColor(255) + ","
  + randomColor(255) + ","
  + randomColor(255) + ")";
  }

  function randomColor(num) {
    return Math.floor(Math.random() * num);
  }

  function resetColorOfBoxes() {
    boxes = document.querySelectorAll('div');
    boxes.forEach(box => box.style.backgroundColor = "white");
  }

  function promptEntry() {

    let userInput = prompt("How many rows would you like?", "Enter a number");

    if (isNaN(userInput)) {
      alert("That's not a valid entry. Try again");
      promptEntry();
    }

    else {
      createGrid(userInput);
    }
  }

  function createGrid(numberOfRows) {

    resetColorOfBoxes()

    /*Change number of grid-template-columns and grid-template-rows under #container in stylesheet*/
    document.documentElement.style.setProperty("--columns-row", numberOfRows);

    let i = 0;
    let numberOfBoxes = numberOfRows**2;

    /*Create boxes*/
    for (i; i < numberOfBoxes ; i++) {
      var div = document.createElement("div");
      document.getElementById("container").appendChild(div);
      div.addEventListener("mouseenter", function () {
        randomRgb();
        this.style.backgroundColor = col;
        console.log(value);
      });
    }
  }

  let btn = document.getElementById("start")
  btn.addEventListener("click", promptEntry)

  </script>
</html>

This is the prompt (taken from theodinproject.com):

(Optional): Instead of just changing the color of your grid from black to white (for example) have each pass through it with the mouse change to a completely random RGB value. Then try having each pass just add another 10% of black to it so that only after 10 passes is the square completely black.

Thank you!


Solution

  • I think you are on the right track.

    One way to go about it NOTE: I've removed most of the wrapping code, so you could get the concept and style it afterward as you wish.

    function randomRgb() {
      return `rgb(${randomInt(255)},${randomInt(255)},${randomInt(255)})`;
    }
    
    function rgb2hex(rgb) {
      rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
      return (rgb && rgb.length === 4) ? '#' +
        ('0' + parseInt(rgb[1], 10).toString(16)).slice(-2) +
        ('0' + parseInt(rgb[2], 10).toString(16)).slice(-2) +
        ('0' + parseInt(rgb[3], 10).toString(16)).slice(-2) : '';
    }
    
    function randomInt(num) {
      return Math.floor(Math.random() * num);
    }
    
    /**
    * @param color {string} HEX color
    * @param amount {number}Can be negative for lighter color or positive for darker 
     * @return {string}
     */
    function lightenDarkenColor(color, amount) {
      let usePound = false;
      if (color[0] === '#') {
        color = color.slice(1);
        usePound = true;
      }
      const num = parseInt(color, 16);
      let r = (num >> 16) + amount;
      if (r > 255) r = 255;
      else if (r < 0) r = 0;
      let b = ((num >> 8) & 0x00FF) + amount;
    
      if (b > 255) b = 255;
      else if (b < 0) b = 0;
    
      let g = (num & 0x0000FF) + amount;
      if (g > 255) g = 255;
      else if (g < 0) g = 0;
    
      return (usePound ? '#' : '') + (g | (b << 8) | (r << 16)).toString(16);
    
    }
    
    function createGrid(num) {
      const container = document.getElementById('container');
      for (let i = 0; i < num; i++) {
        const div = document.createElement('div');
        // Remove the next line, just for the demo
        div.innerHTML = `${i}`;
        const defaultColor = randomRgb();
        const hex = rgb2hex(defaultColor);
        const altColor = lightenDarkenColor(hex, -10);
        div.style.backgroundColor = defaultColor;
        // Remove the next line, just for the demo
        div.style.padding = '20px';
        div.onmouseout = function() {
          div.style.backgroundColor = defaultColor;
        };
        div.onmouseover = function() {
          div.style.backgroundColor = altColor;
        };
        container.appendChild(div);
      }
    }
    createGrid(10);
    <h1>Please hover over the boxes </h1>
    <div id="container"></div>