I'm curious why my background generator is only altering a portion of the background instead of the entire thing

I've been attempting to create a JavaScript random background changer, but I'm encountering some challenges. The main issue is that instead of changing the entire page's background, it only alters a strip of it. Additionally, I'm curious about how to make the button clickable multiple times to continuously randomize the background. Currently, after clicking once, I have to refresh the page to trigger another change.

let btn = document.getElementById('btn');

let randomR = parseInt(Math.floor(Math.random() * 255))
let randomG = parseInt(Math.floor(Math.random() * 255))
let randomB = parseInt(Math.floor(Math.random() * 255))

function backColor() {
  document.body.style.backgroundColor = 'rgb(' + randomR + ',' + randomG + ',' + randomB + ')';
}

btn.addEventListener('click', backColor)
* {
  text-align: center;
  margin: 3% auto;
  color: #fff;
  background-color: #F07DEA;
}

button {
  height: 40px;
  width: 100px;
  border: solid 2px #000;
  border-radius: 5px;
  background-color: #EEEEEE;
  color: #000;
}

button:hover {
  background-color: #000;
  color: #fff;
  border: solid 2px #fff;
}
<body>
  <button class="btn-class" id="btn" onclick="backColor()">
    Click Me!
  </button>
</body>

Answer №1

In order to continuously recalculate the random R, G, and B values whenever clicked, it is necessary for those variables to be declared within the backColor function. By doing so, they will be dynamically recalculated each time the function is called, rather than being computed only once during the initial page load.

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

Concentrate on the HTML element once it becomes active

I am facing a challenge where I need to focus on a specific input element. However, there is a spinner that appears on page load and remains hidden until certain http requests are completed. All inputs are disabled until the requests are finished. The setu ...

The issue of jQuery Validation repeatedly displaying the same error messages upon clicking the submit button

After implementing the jQuery Validation plugin on my website, I noticed that when I click the Submit Button without filling in the required text boxes, the required field message displays multiple times. For example, if I click the Submit button three ti ...

Using a JavaScript variable to be displayed in a PHP code

Can someone please help me troubleshoot this code? I am attempting to display a JavaScript variable in PHP after applying a regex, but I keep getting the error Uncaught TypeError: document.getElementById(...).html is not a function $.post('display.ph ...

New solution for Java applet requiring communication with browser using JavaScript

Within our web platform, we have been utilizing a Java applet to interact with the MS Word application using jacob jar. This allows users to open, edit, and automatically upload files to the server upon saving. However, due to Google Chrome discontinuing ...

Verify if the username or phone number is already in use (front end)

Is there a way to verify user or phone existence on the front-end form? I'm using Yup + Formik for all my requirements, and in my backend with Sequelize, I can check if a username or phone number already exists. passport.use( 'register&apos ...

The post request fails to send certain variables

I'm experiencing an issue with a form that has rows structured like this: <div class="row unit" onmouseover="this.style.background = '#eeeeee';" onmouseout="this.style.background = 'white';" onclick="if(event.srcElement.nodeNam ...

Centering H1 and dropdown button horizontally using Bootstrap

I positioned a dropdown button next to an H1 tag, but I noticed that they are not perfectly aligned and I want to move the dropdown button up slightly. My project is utilizing Bootstrap 5.1.3 https://i.sstatic.net/muIwB.png <div class="ps-4 pt-4 ...

Organize and categorize items

I need help sorting an object displayed below. My goal is to calculate the sum of all rating properties for each object, and then sort the objects based on the highest total rating. For instance, if the total rating for Intro 1 is 7 and for Intro 2 is 3, ...

Are instance prototypes exhibiting static behavior?

I'm in the process of creating a game for Windows 8 using HTML/Javascript and WinJS, but I'm running into issues with "prototypes" acting statically when they shouldn't. This is my first time working extensively with Javascript and dealing w ...

Is the in-app browser of WeChat able to support self-signed HTTPS URLs?

My local WAMP server hosts a web application with self-signed SSL enabled, resulting in the following app URL: https://myipaddress:port/demoapp/index.html However, when I send this URL via WeChat chat and click on it, only a blank page is displayed. Stra ...

Set the webpage to a fixed width

Is there a way to make my webpage fixed-width instead of liquid? I've tried changing the container size to pixels but the text still collapses when I resize the browser. Any suggestions on how to keep it at a fixed width? <!DOCTYPE html PUBLIC "-/ ...

What is the best way to neatly import multiple images in Next.js?

I have a dilemma involving 10 images located in my public directory that I need to use in a component. Instead of individually importing each image like this: import imgurl1 from "../../public/celsius.gif"; import imgurl2 from "../../public/ ...

Use Javascript or Jquery to dynamically change the background color of cells in HTML tables based on their numerical

I am working with a collection of HTML tables that contain numbers presented in a specific style: <table border="1"> <tr> <th>Day</th> <th>Time</th> <th>A</th> <th>B</th> &l ...

Encountering limitations in accessing certain object properties with the openweathermap API

As I integrate axios into my react application to retrieve weather data from the openweathermap api, I'm encountering some issues with accessing specific properties from the JSON object returned by the API call. For instance, I can easily access data. ...

Is it possible to include a module-level controller within a directive?

I am currently navigating the complexities of controllers, modules, and services in Angular JS. In my attempt to integrate a controller into my directive, I faced an issue. The controller I intend to reference belongs to the same module as the directive, ...

Guide on jQuery: Concealing the scrollbar on the body

Is there a way to hide the scroll bar using Jquery? I tried this code for Chrome but need a solution that works for all browsers. $ ::-webkit-scrollbar { display: none; } Any suggestions on how to achieve this cross-browser compatibility? ...

Exploring the process of traversing a function for each ng-repeat element

Hey everyone, I'm currently facing an issue where I need to pass each date through a function in order to get the desired result. Let's take a closer look at the code snippet: <md-list> <md-divider ></md-divider> ...

Why am I receiving a null response from my ajax request?

I have a working ajax call to fetch XML data from my REST API. However, when I try to echo the results, JQuery returns null. If I use var_dump on the results instead, JQuery accepts the information but it's not formatted correctly and causes errors. ...

Failed to input data into MySQL database's dynamic field

I have encountered an issue while trying to enter dynamic fields into a MySQL database, and I am struggling to figure out the cause of the problem. Below are both the HTML and PHP files provided; I would greatly appreciate any assistance in identifying and ...

Execute a JavaScript function when a text input field is changed and after a certain

Can someone help me with this code snippet? $(document).ready(function() { var timeoutId; $('#invoices input, #invoices textarea').on('input propertychange change', function() { clearTimeout(timeoutId); time ...