Elevate the value of a particular element's variable through the execution of a function

By using a for loop, I was able to generate a variable number of divs that change their background color individually when hovered over with the mouse. Now, I want to implement a function that will decrease the brightness of each div by 10% every time it is hovered over. Unfortunately, my attempts have only resulted in decreasing the brightness of all divs simultaneously rather than individually. I apologize for the confusion in my explanation and would be grateful for any assistance.

<!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!

Answer №1

It seems like you're heading in the right direction.

Here's a way to approach it: NOTE: The wrapping code has been omitted for clarity. Feel free to style it according to your preferences.

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to convert PDF documents to HTML using languages such as C, C++, or Java?

My current project involves annotating HTML files using Javascript, and I need to convert PDF files into HTML files specifically for the IOS platform. While I have had some success in annotating HTML pages, I am unsure how to go about converting PDF to H ...

Using Node.js to dissect a nested JSON array into individual JSON objects

Seeking guidance on how to efficiently parse nested arrays into separate objects using Node.js. Your assistance would be greatly appreciated. I aim to exclude the following from the final output- "Status": "0", "Message": "OK", "Count": "3724", AND I w ...

The positioning of the Bootstrap dropdown menu is not aligned correctly

Issue with positioning Bootstrap dropdown I recently encountered a problem where I placed a bootstrap dropdown inside a div that centers the dropdown using CSS "text-align: center", but the dropdown menu still appeared in its original position. It seems l ...

Error: An unexpected 'if' token was not caught

Encountering an error related to the question title while working with this code snippet: $LAB.queue(function setup() { FB.init({ appId: '00000000', status: true, cookie: true, xfbml: true, logging: &ap ...

Encountering a ReferenceError stating that the window object is not defined while building a React Leaflet application

In my upcoming nextjs project, I've incorporated react-leaflet. It behaves flawlessly in dev mode. However, upon attempting to build the project, it throws a ReferenceError: window is not defined. Despite setting ssr to false in dynamic, the error per ...

Steps for triggering a logout using MSAL2Provider

Currently, I am incorporating the React Login Microsoft-Graph-Toolkit component (shown in the code snippet below) along with MSAL2Provider to facilitate user login functionality in my Active Directory application. Although this setup is functioning smoothl ...

Steps for importing a json file into Chrome

Inside my file named data.json, there is a JSON object structure: { "k": : "..some object...", "a": [ "...", "bbb" ] } When working with Node.js, I can easily import this data into a variable using: let data = require("./data.json"); However, how can I ...

How can I use PHP to send the user to another PHP file?

After searching for answers with no luck, I ended up coming here to ask my question. Here is the code snippet in question : <a href="manage/10000' . $user["user_id"] . ' " class="user_grop">More Info</span></a> I am wondering ...

Unable to get CSS First Child Pseudo Element to Work Properly

I'm having trouble with this code in CSS and would appreciate any help. I can't figure out why the margin-left won't apply to the first i element. Below is the CSS I'm using: header.site-header .right_side_menu i:first-child { marg ...

Increase the value by one of the number enclosed in the <h3> element

I have a variable number of <h3> tags with the same class .love_nummer <h3 class="love_nummer">1</h3> Each of these tags contains a number, and alongside each .love_nummer tag is another tag with the class .give_love <h3 class="give ...

Increasing the value of a TypeScript variable using ngFor in an HTML template can enhance its usefulness

Can you dynamically increase a variable declared in your TypeScript file for each element generated by an ngFor loop in your HTML file? <tbody> <tr *ngFor="let item of invoiceItems"> <td>{{item.ItemName}}</td> <td>{ ...

Tips on how to add a file input type:

When working with my HTML code, I encountered an issue. When I change the type attribute to "text", everything works fine. However, when I change it to "file", nothing happens when I click. <input type="file" name="pic[]" accept="image/*">a <inpu ...

Sending an HTTP request from within an Express/Node.js application

I am currently in the process of setting up an express service for a program I am developing. The goal is to interact with an external API, retrieve the data, and store it in a MongoDB database that I have already set up. While this task may seem straight ...

"Encountering a Prisma type error while attempting to add a new record

I am currently utilizing Prisma with a MySQL database. Whenever I attempt to create a new record (School), an error of type pops up in the console. Additionally, I am implementing a framework called Remix.run, although it does not seem to be causing the is ...

Remove all objects from a model based on a specific value by implementing a button in Django

For reference, please take a look at the table screenshot: https://i.sstatic.net/evBSK.png I am attempting to remove a row from the table using the corresponding Delete Asset button (meaning deleting all rows in a django model with Symbol: 1INCHUP) The s ...

Use JQuery to constantly monitor for any changes in HTML Div

I am dealing with a browser-based chat application where separate div elements are generated for each chat conversation. An external module oversees the entire chat process, and I do not have access to its underlying code. It is important to note that the ...

What steps can be taken to stop images from overflowing a flex-grow-1 item?

https://i.sstatic.net/1Qgec.pngHello, I'm facing an issue with my image. I am dealing with 3 sections: Main Content Image and other components (main section) Button Currently, I need to ensure that the image height is set to a maximum of 100% of the ...

Using HTML's select option to submit a request for data retrieval from PHP using PDO with MySql database

I am having an issue with fetching data from MySQL based on Select Month and Year in HTML Select Option. When I submit the view, the table should be filtered accordingly. Otherwise, all data should be displayed. However, my code is generating an error. No ...

The left-hand operator in Typescript is not valid

I am a beginner in typescript and I have been following a tutorial called Tour of Heroes on Angular's website. In the final chapter of the tutorial, when I tried to use HTTP with the provided code, everything seemed to run fine but I encountered an er ...

A JavaScript function written without the use of curly braces

What makes a function good is how it is declared: export declare class SOMETHING implements OnDestroy { sayHello() { // some code to say hello } } However, while exploring the node_modules (specifically in angular material), I stumbled up ...