Swirling hues transforming into #000000 upon second attempt

My goal is to create a button that generates two random color codes. Initially, this button seems to work fine on the first click, but on the second click, both codes turn into #000000.

Despite my attempts to troubleshoot the issue, I haven't been able to find a solution. I would greatly appreciate any advice on how to fix this problem.

var css = document.querySelector("h3");
var color1 = document.querySelector(".color1");
var color2 = document.querySelector(".color2");
var body = document.getElementById('gradient')
var random1 = document.getElementById("random1");
var random2 = document.getElementById("random2");
var colorGenerator = "1234567890ABCDEF";
var colortag1 = "#";
var colortag2 = "#";
...


Color1.addEventListener("input", backgroundcolor);
Color2.addEventListener("input",backgroundcolor);
Random1.addEventListener("click", randomColor);
body {
font: 'Raleway', sans-serif;
    color: rgba(0,0,0,.5);
    text-align: center;
    text-transform: uppercase;
    letter-spacing: .5em;
    top: 15%;
background: linear-gradient(to right, red , yellow); /* Standard syntax */
}

h1 {
    font: 600 3.5em 'Raleway', sans-serif;
    color: rgba(0,0,0,.5);
    text-align: center;
    text-transform: uppercase;
    letter-spacing: .5em;
    width: 100%;
}

h3 {
font: 900 1em 'Raleway', sans-serif;
    color: rgba(0,0,0,.5);
    text-align: center;
    text-transform: none;
    letter-spacing: 0.01em;

}

button {
    color: rgba(0,0,0,.5) ;
    font: 800 1em 'Raleway', sans-serif;
    background-color: transparent;
    border: none;
    overflow: hidden;
    outline: none;
}
<!DOCTYPE html>
<html>
<head>
<title>Gradient background</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body id="gradient">
<h1>Backround Generator</h1>
<input class="color1" type="color" name="color1" value="#FF0000">
<input class="color2" type="color" name="color2" value="#FFFF00">
<h2>Current CSS Background</h2>
<button id="random1">Random Colors</button>

<h3></h3>
<script type="text/javascript" src="script.js"></script>
</body>
</html>

Answer №1

When working with the snippet code:

for (i = 0; i < 6; i++){
        colortag1 += colorGenerator[Math.floor(Math.random() * 16)];
        colortag2 += colorGenerator[Math.floor(Math.random() * 16)];
        color1.value = colortag1;
        color2.value = colortag2;
    }

It is important to note that by appending to the color tag (colortag1 +=), the resulting value will be something like '#7C247EEC3C75' on the second iteration. To avoid this, make sure to assign the variable to an empty string before the loop.

colortag1 = "#";
colortag2 = "#";
for (i = 0; i < 6; i++){
        colortag1 += colorGenerator[Math.floor(Math.random() * 16)];
        colortag2 += colorGenerator[Math.floor(Math.random() * 16)];
        color1.value = colortag1;
        color2.value = colortag2;
    }

I trust this solution will be beneficial for your project.

Answer №2

According to Santiago Casas Rey, you should remember to reset colortag1 and colortag2. It's important to maintain organized code to avoid unnecessary confusion, especially when using Math.random(). Personally, I find rando.js helpful for simplifying and improving the readability of randomness. To generate a random hex string with rando.js, you can use the following code snippet:

function randomHex(){
  var hex = "#";
  for(var i = 0; i < 3; i++) hex += ("0" + rando(255).toString(16)).slice(-2);
  return hex;
}

console.log(randomHex());
<script src="https://randojs.com/1.0.0.js"></script>

If you prefer a one-liner, you can use the following code:

console.log( "#" + ("0" + rando(255).toString(16)).slice(-2) + ("0" + rando(255).toString(16)).slice(-2) + ("0" + rando(255).toString(16)).slice(-2) );
<script src="https://randojs.com/1.0.0.js"></script>

Applying this concept to your JavaScript code:

var css = document.querySelector("h3");
var color1 = document.querySelector(".color1");
var color2 = document.querySelector(".color2");
var body = document.getElementById('gradient')
var random1 = document.getElementById("random1");

function randomHex() {
  var hex = "#";
  for (var i = 0; i < 3; i++) hex += ("0" + rando(255).toString(16)).slice(-2);
  return hex;
}

function changeToColors(hex1, hex2){
  body.style.background = "linear-gradient(to right," + hex1 + "," + hex2 + ")";
  css.textContent = body.style.background;
}

function changeToInputColors() {
  changeToColors(color1.value, color2.value);
}

function changeToRandomColors() {
  changeToColors(randomHex(), randomHex());
}

changeToInputColors();

color1.addEventListener("input", changeToInputColors);
color2.addEventListener("input", changeToInputColors);
random1.addEventListener("click", changeToRandomColors);
body {
  font: 'Raleway', sans-serif;
  color: rgba(0, 0, 0, .5);
  text-align: center;
  text-transform: uppercase;
  letter-spacing: .5em;
  top: 15%;
  background: linear-gradient(to right, red, yellow);
  /* Standard syntax */
}

(remaining CSS code omitted for brevity)
<!DOCTYPE html>
(remaining HTML code omitted for brevity)
</html>

Don't forget to include the following line in the head tag of your HTML document to use this code:

<script src="https://randojs.com/1.0.0.js"></script>

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

Switching from HTML to PHP programming

Trying to build a website from scratch and incorporate a form has been challenging. My goal is for the Submit button to send an email without launching any email program, but I'm facing redirection issues. Despite searching on Google for solutions, I ...

How can I indicate to the browser that the HTML page should be accessed through SSL?

I've set up a certificate on my website. Now, I only want one specific page to be accessed through SSL. Do I need to add any markup on the page itself, or is there another setting elsewhere that I should use? ...

Utilizing External Libraries in SAPUI5 Extension Development

I am facing an issue while trying to integrate an external library into my UI5 project. Specifically, I am working with jsPDF but it could be any other library as well. I have included it in the manifest.json file in the following manner: "js": [{ ...

What is the best way to update or include a new class in the jQuery mobile loader widget?

After reviewing the documentation at this link: I discovered a method to modify or add the default class of the loader widget, ui-loader. Despite my attempts, I have not been able to see any changes. You can view my demo here: https://jsfiddle.net/yusril ...

Ways to identify the moment jQuery datatable is initialized and populated with information

I am currently using the most recent version of jQuery datatables. I'm curious if there is a callback function available that triggers right after the data has been loaded and displayed in the table? While experimenting with a datatable in IE8, I hav ...

Combining array elements into sets of n

I am facing a challenge with an array manipulation task. let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]; My goal is to divide this array into a specified number of smaller arrays such that each new array contains the same number of elements ...

What is the best way to display or hide specific tables depending on the button chosen?

Being fairly new to JavaScript, I find myself unsure of my actions in this realm. I've successfully implemented functionality for three links that toggle visibility between different tables. However, my ideal scenario would involve clicking one link t ...

Replace the plus signs in a string with spaces using the JSON.stringify method

When utilizing AJAX, I am sending the string someString to a PHP handler. xmlHttp.open("POST", url, true); var someString = 'Foo+Bar'; var params = 'operation='+operation+'&json='+JSON.stringify(someString); xmlHttp.send( ...

What is the best way to begin an ordered list from the number 2 instead of 1, while ensuring W3C validity and compatibility with

Is it possible to start an ordered list from 2 instead of 1? I need the solution to be compatible with all browsers, including IE6, and ensure that the HTML and CSS are valid. ...

What steps can be taken to halt an ongoing AJAX call and initiate a new one with different parameters?

I recently implemented an ajax call using the jQuery.everyTime() function. The setup involves a combo box where users can select different graph names, triggering dynamic calls to an ajax function that returns JSON data and populates a chart in the View ev ...

Analyzing and tallying JSON attributes using JavaScript

I have a JSON object with items that I need to analyze in JavaScript. When I view the JSON in the console, there is an element called items that contains an array of relevant information. console.log(json) {current_page: 1, per_page: 100, total_entries: ...

Adjusting the URL variable based on the selected checkbox option

My mobile website offers users the option of a bright or dark interface using a checkbox styled like an iPhone IOS7 switch. The functionality is working as expected, but I'm now facing an issue with passing the status of the checkbox between pages. I ...

Managing user input in Node.js

Users are required to input a URL in the form (e.g: "") and I need to be able to access and read the content from that URL. I am uncertain about my current method. What should I enter in the URL field below? var options = { url: '....', ...

Analyzing and swapping objects within two arrays

Looking for a better way to append an array of objects customData to another array testData? If there are duplicate objects with the same name, replace them in the resulting array while maintaining their order. Here's my current approach in ES6 - any ...

What is the best way to incorporate the PUT method...?

Within the realm of programming, there exist three distinct files with specific roles - profiles.model.js, profiles.controller.js, and profiles.router.js. The focus now shifts towards implementing the PUT method across these three files. To begin, profiles ...

Disable touch interactions on the body, only allow pinch-zoom on specific elements

I have been attempting to implement the following code: body { touch-action: none; } .left-side { touch-action: pinch-zoom; } <div class="left-side"><img src="image.jpg" /></div> The touch-action: none is functioning properly, but ...

What drawbacks come with developing an Express.js application using TypeScript?

Curious about the potential drawbacks of using TypeScript to write Express.js applications or APIs instead of JavaScript. ...

The cursor in a contenteditable element fails to return to its original position after adding a new line and then deleting it

I have come across a basic HTML code snippet: span { outline: none; } hello <span contenteditable="true"> world </span> Upon testing, I observed that each time I press ENTER within the contenteditable span, the cursor moves to a new ...

Conceal the ::before pseudo-element when the active item is hovered over

Here is the code snippet I am working with: <nav> <ul> <li><a href="javascript:void(0)" class="menuitem active">see all projects</a></li> <li><a href="javascript:void(0)" class="menuitem"> ...

What is the best way to update the style following the mapping of an array with JavaScript?

I want to update the color of the element "tr.amount" to green if it is greater than 0. Although I attempted to implement this feature using the code below, I encountered an error: Uncaught TypeError: Cannot set properties of undefined (setting 'colo ...