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

Playing audio from local blob data is not supported on mobile browsers

I'm trying to stream blob data in mp3 format, but I'm experiencing difficulties with mobile browsers. The code below works perfectly on PC browsers, but not on mobile: // Javascript var url = URL.createObjectURL(blob); audio = document.getEleme ...

Issue encountered when transferring properties to create a search bar

My goal is to create a search input that filters based on the user's input. I have two components - one with the search input (app.js) and the other with the table (table.js). In the search input component (app.js), I can retrieve the current value b ...

Why does a relatively positioned element always begin at the top corner of the window?

I am really struggling to understand the concept of relative versus absolute positioning, especially when dealing with parent or grandparent elements that have position values. Can someone please help me clarify these two scenarios: Case 1: grandparent ...

Error message is not shown by React Material UI OutlinedInput

Using React and material UI to show an outlined input. I can successfully display an error by setting the error prop to true, but I encountered a problem when trying to include a message using the helperText prop: <OutlinedInput margin="dense&quo ...

Printing the result of an SQL query in Node.js without using braces

As a beginner in node.js with only a basic understanding of javascript, I apologize if I make any mistakes. I attempted to display the results retrieved by an SQL query in node.js using: <p>Users are " + util.inspect(results) + ".</p>" an ...

Creating a switch statement that evaluates the id of $(this) element as a case

I have a menu bar with blocks inside a div. I am looking to create a jQuery script that changes the class of surrounding blocks in the menu when hovering over a specific one. My idea is to use a switch statement that checks the ID of $(this) and then modif ...

Guide to displaying API data in HTML format

This university assignment involves working on a homework project where I need to utilize a public API in HTML. So far, I have successfully called the public API to display a list of radio channels in the left menu (without adding any click functionality). ...

Changing the mouse cursor dynamically with Angular programming

What is the recommended approach for changing the mouse cursor programmatically in Angular? For instance: HTML: <div [style.cursor]="cursorStyle">Content goes here</div> or <div [ngStyle]="{ 'cursor': cursorStyle ...

Using the <audio> tag in HTML5 on Android devices

Exploring discussions on Android's support for the <audio> tag has been enlightening. Despite attempts on a Nexus One running Android Froyo 2.2, it seems playing audio remains elusive. As indicated by www.html5test.com, while the tag is support ...

Creating a full-screen background with an rgba overlay using CSS

I recently encountered an issue with a fixed, fullscreen background image on my website. I initially applied the background image to the HTML's CSS instead of the body's CSS. To add a black overlay with lowered opacity, I included the following c ...

Unpredictable selection of elements displayed as links

As someone who is relatively new to PHP and HTML, I am working on a website that features a product of the week. However, I have hit a roadblock in implementing my idea. My concept involves creating an array with various products and using array_rand to s ...

What is the best way to choose a specific section of a string using JQuery?

When utilizing the .html() function to retrieve html code, I encounter a need to extract a specific segment of the string. var newImgAdr = $(this).html(); The variable newImgAdr currently consists of: <img class="thumbnail-holder image-responsive cen ...

Generate a menu submenu allowing for interactive toggling and dynamic visualization of expandable/collapsible sections upon clicking, featuring visually

Looking for assistance in creating a dynamic menu with sub-menus that can expand upon clicking. The goal is to have an expandable menu structure where the user can click to expand or collapse certain sections. However, my current code is not functioning co ...

Send the DOM element to a processing function within AngularJS

In this code snippet, there is an attempt to pass a table cell (as a DOM object) to a function. However, it seems that the reference of 'this' does not point to the DOM object for the table cell, but rather to '$scope'. Any suggestions ...

Adjust the dimensions of an element using Protractor

When using the getSize method, I am able to determine the size of an element but I am struggling to understand how to change its height. To provide some additional context, my goal is to verify if a user can resize a textarea element. Should I simply adju ...

What steps can be taken to execute a function when a button remains unclicked?

$("#RunCode").click(function(){ var $this = $(this); if($this.data('clicked')) { console.log("Is clicked"); $(".documentWrite").text("Is clicked"); } else { $this.data('clicked', true); consol ...

Which option's value was recently removed from the fetch command?

I created a function to handle duplicate selections in a select element. It is functioning properly, but I noticed that when I remove an option from the select, my array remains unchanged. If I remove an option, I want my code to detect the value of that ...

The media query designed for iPads with a minimum width will also be effective for Android devices

As I delve into the realm of editing CSS created by others, I come across a peculiar situation involving media queries specifically designed for iPads. While one query is intended for portrait orientation and another for landscape, they are causing havoc o ...

Challenges with incrementing in Jquery's each loop and setTimeout

http://jsfiddle.net/fxLcy/ - an example showcasing the use of setTimeout. http://jsfiddle.net/fxLcy/1/ - this demo does not include setTimeout. Although all elements are correctly positioned, I am in need of that delayed animation =/ My goal is to arrang ...

Is the Javascript file successfully loaded?

Is there a way to verify if all 8 javascript files are loaded in an html document and handle any errors that may occur if one of the files fails to load, across various browsers? Thank you for your help! ...