What steps can I take to prompt this function to modify the value of my input?

After recently delving into the world of JavaScript, I decided to create a background color generator that randomly changes when a button is clicked. This simple project involves two input fields (color1 & color2) which receive random values upon clicking the button, updating the body's style accordingly.

Here's the code: HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="style.css">
    <title>Gradient Background</title>
</head>
<body id="gradient">
    <div class="container">
        <h1>Background Generator</h1>
        <input class="color1" id="color1" type="color" name="color1" value="#ff0000">
        <input class="color2" id="color2" type="color" name="color2" value="#ffff00">

        <h2>Current CSS Background</h2>
        <h3></h3>
        <button id="button" class="button">Randomize</button>
    </div>

    <script src="script.js"></script>
</body>
</html>

JavaScript:

var css = document.querySelector("h3");
var color1 = document.querySelector(".color1");
var color2 = document.querySelector(".color2");
var body = document.getElementById("gradient");
var button = document.getElementById("button");
var inputColor1 = document.getElementById("color1");
var inputColor2 = document.getElementById("color2");

function setGradient() {
    body.style.background = "linear-gradient(to right," + color1.value + "," + color2.value + ")";

    css.textContent = body.style.background + ";";
}

color1.addEventListener("input", setGradient);
color2.addEventListener("input", setGradient);


inputColor1.value = generateRandomColor().value;
inputColor2.value = generateRandomColor().value;

function generateRandomColor(){
    let maxVal = 0xFFFFFF; // 16777215
    let randomNumber = Math.random() * maxVal; 
    randomNumber = Math.floor(randomNumber);
    randomNumber = randomNumber.toString(16);
    let randColor = randomNumber.padStart(6, 0);   
    return `#${randColor.toUpperCase()}`
}
// console.log(generateRandomColor()); 

button.addEventListener("click", generateRandomColor);

Thanks ;)

Answer №1

If you want to randomize two colors, make sure to call the generateRandomColor function twice instead of just once. After obtaining the random values for both colors, set them to their respective inputs and then trigger the setGradient function again.

const css = document.querySelector("h3");
const color1 = document.querySelector(".color1");
const color2 = document.querySelector(".color2");
const body = document.getElementById("gradient");
const button = document.getElementById("button");
const inputColor1 = document.getElementById("color1");
const inputColor2 = document.getElementById("color2");

function setGradient() {
  document.body.style.background = "linear-gradient(to right, " + color1.value + ", " + color2.value + ")";

  css.textContent = document.body.style.background + ";";
}
setGradient();

color1.addEventListener("input", setGradient);
color2.addEventListener("input", setGradient);
function generateRandomColor() {
  const maxVal = 0xFFFFFF; // 16777215
  const randomNumber = Math.floor(Math.random() * maxVal).toString(16);
  const randColor = randomNumber.padStart(6, 0);
  return `#${randColor.toUpperCase()}`
}
button.addEventListener("click", () => {
  inputColor1.value = generateRandomColor();
  inputColor2.value = generateRandomColor();
  setGradient();
});
<div class="container">
  <h1>Background Generator</h1>
  <input class="color1" id="color1" type="color" name="color1" value="#ff0000">
  <input class="color2" id="color2" type="color" name="color2" value="#ffff00">

  <h2>Current CSS Background</h2>
  <h3></h3>
  <button id="button" class="button">Randomize</button>
</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

Repairing a CSS file for Internet Explorer versions 7, 8, and 9

Does anyone have experience with troubleshooting HTML5 CSS3 layouts across different browsers? I recently created a website layout from scratch that looks perfect in Firefox 5, Safari 5.1 and Chrome 12 on Mac. However, when using tools like Adobe BrowserL ...

Issue with isNan() and typeof in React framework

I'm attempting to create a field in the react-bootstrap component that only accepts numeric input. I know there is a type="number" attribute that can be used, but it's currently set to password to mask the input. Initially, I tried this approach ...

Tips for smoothly transitioning from a simple transform to a rotate effect

I need help with an HTML element that needs to rotate when hovered over. Here is the code I have: The issue I'm facing is that I don't want a transition for translateX, only for the rotation. What steps should I take to achieve this? .cog { ...

Executing a background.js function in response to an event trigger within the active tab in a Chrome extension

I am facing an issue where I am getting an error saying "resetTime is not defined" when running the code below. I have tried passing the function as an argument, but that did not solve the problem. Do I need to come up with a new logic to reset the time ...

Can you align a row under its corresponding column in Bootstrap?

Hello, I'm facing a dilemma with my layout. I have a grid consisting of 2 Rows and 4 Columns (col-md-8 & col md-4 in each row). The structure is as follows: Within the container Row 1 Column 1 (md-8) Row 1 Column 2 (md-4) [Accordion] Row 2 Colum ...

How to position a fixed element in relation to a wrapper div using HTML and CSS

I need assistance with positioning the floating box on the right side of the window on this particular page. My goal is to have this box relative to the white div containing all the text, so instead of it sticking to the window edge, it should float aroun ...

The forecast button seems to be malfunctioning. Each time I attempt to click on it, a message pops up saying, "The server failed to comprehend the request sent by the browser (or proxy)."

Even though I provided all the necessary code, including the Flask app, predictionmodel.py, and HTML code, I am still encountering an error when running it locally after clicking submit. The browser (or proxy) sent a request that this server could not un ...

Bug Alert: Incompatibility between Angular $resource and PHP causing issues with Update and Delete functionalities

As a newcomer to both AngularJS and PHP, I have been struggling to find comprehensive documentation on using $resource to update records in a database. While I did come across a helpful tutorial here that covers most aspects of $resource usage, I am having ...

"Converting HTML code into visual templates for browser display - a step-by-step guide

I have a task to transform HTML into a template format. As shown in the image, the content needs to be displayed as a template. I currently use a table for display, but now I want to present it in a template output. Below is the code snippet: <table ...

Issue encountered when attempting to execute a JavaScript AppleScript from another JavaScript AppleScript due to permissions error

I am in the process of organizing my .applescript files by separating them into different ones for better organization. Within my JS AppleScript file named Test.applescript, I am attempting to execute another JS AppleScript file called Group Tracks Depend ...

Material-UI: The `paperFullWidth` key passed to the classes prop is not supported within the WithStyles(ForwardRef(Dialog)) component

When using Material-UI, please note that the key paperFullWidth provided to the classes prop is not implemented in WithStyles(ForwardRef(Dialog)). You are only able to override one of the following: root. <Dialog classes={{ paperFullWid ...

Ajax fails to function within a loop

I'm looking to implement Ajax in a loop to retrieve data sequentially. This is what I have in my JavaScript function: var resultType = $("input[name='resultType']:checked").val(); var finalResult = ""; var loadingMessage = "<img src=&ap ...

Troubleshooting the lack of functionality with justify-items in CSS Grid

I'm facing an issue with my CSS Grid. I am attempting to set the justify-items property to start. Despite referencing the specification and watching a tutorial where it works, the property (and related ones) are not functioning as expected. In my tex ...

Utilizing Ajax for submitting data in a Spring application

I'm attempting to send a PUT request to the controller using AJAX. Here is my code: $().ready(function(){ $('#submit').click(function(){ var toUrl = '/users/' + $('#id').val() + '/profile'; ...

Setting up a function in React to utilize an image stored in state

I have a function in my react component for image classification that retrieves the image from the img tag using document.getElementById: const img = document.getElementById('animal_image');. The image uploaded via the file input updates the sta ...

Exploring the Factory Design Pattern Together with Dependency Injection in Angular

I'm currently implementing the factory design pattern in Angular, but I feel like I might be missing something or perhaps there's a more efficient approach. My current setup involves a factory that returns a specific car class based on user input ...

Issue: Incorrectly calling a hook. Hooks can only be used within the body of a function component. Assistance needed to resolve this issue

import React, { useState } from "react"; const RegistrationForm = () => { const [name, setName] = useState(""); const [password, setPassword] = useState(""); const [email, setEmail] = useState(" ...

What steps are involved in making select fields that change dynamically?

There are two fields available for the user to interact with: size and design. Users have the ability to add more instances of these fields as many times as they desire. Illustration: If I choose M for the size, it will display in the console: Furthermo ...

Header formatting issue when attempting to implement tablesorter plugin

I implemented the widget-scroller and widget column Selector in my table using the table sorter plugin in jQuery. Has anyone encountered a problem like the one shown in this picture? It seems that my table headers do not align with the columns properly an ...

Discovering how to navigate to a link within a web table using Cypress has been a challenge, as I keep receiving the error message stating that the element is not visible due to its CSS property being

Trying to click on the first enabled link in the 'Action' column of a web table has been proving difficult. In the example given, the first two rows do not have an enabled link, so the goal is to click on '8.5 AccountH' https://i.stack ...