What is the best method to choose a random color for the background when a button is pressed?

Does anyone know how to create a button that changes the background color of a webpage each time it is clicked? I've been having trouble with the javascript function in my code. I've tried multiple solutions but nothing seems to work. Could someone please take a look at my code below and help me out?

<body>
 <section class="stencil-class" id="my">
   <span class="A">A</span>
   <span class="S">S</span>
   <span class="I">I</span>
   <span class="Aa">A</span>
 </section>

   <button class="js-change" id="js-button" onclick="getRandomColor()">Change</button>

   <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
   function getRandomColor() {
     var letters = "0123456789ABCDEF";
     var randomColor = "#";
     for(var i = 0; i < 6; i++){
         randomColor += letters[Math.floor(Math.random() * 16777215)]; 
            }
         document.body.style.background-color = randomColor;
         }
   </script>
   </body>

   /*CSS BELOW*/

   :root{
--background-color: #00d9ff;
--font-color: white;
--font-size: 300px;
--text: center;
--font-sizeb: 25px; 
  }
   body{
background-color: #00d9ff;
   }
  .stencil-class{
    text-align: var(--text);
   margin-top: 100px;
   margin-bottom:70px;
   margin-right: 70px;
   margin-left: 70px;
   }
  .A{
   font-size: var(--font-size);
   color: var(--font-color);
   font-family: Sans-serif;
   }
  .S{
    font-size: var(--font-size);
    color: var(--font-color);
    font-family: Sans-serif;
   }
  .I{
    font-size: var(--font-size);
    color: var(--font-color);
    font-family: Sans-serif;
   }
  .Aa{
    font-size: var(--font-size);
    color: var(--font-color);
    font-family: Sans-serif;
   }
   .js-change{
    border: 3px solid #000000;
    background-color: #00d9ff;
    color: var(--font-color);
    text-align: var(--text);
     margin-left: 570px;
     padding: 25px;
    font-size: var(--font-sizeb);
 }

Answer №1

Make sure to utilize

document.body.style.backgroundColor
in place of
document.body.style.background-color
,

Furthermore, switch out 16777215 with letters.length,

function generateRandomColor() {
  var letters = "0123456789ABCDEF";
  var randomColor = "#";
  for (var i = 0; i < 6; i++) {
    randomColor += letters[Math.floor(Math.random() * letters.length)];
  }

  document.body.style.backgroundColor = randomColor;
}
<section class="stencil-class" id="my">
  <span class="A">A</span>
  <span class="S">S</span>
  <span class="I">I</span>
  <span class="Aa">A</span>
</section>

<button class="js-change" id="js-button" onclick="generateRandomColor()">Change</button>

Answer №2

Someone pointed out a mistake in your background color, but here's a shorter version of what you're looking for:

<button class="js-change" id="js-button" onclick="getRandomColor()">Change</button>
<script>
function getRandomColor() {document.body.style.backgroundColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);}
</script>

related SO question

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

What is the reason behind my phone burger not working and how can I resolve the problem?

I am facing an issue with the burger menu icon on my website. When I click on the burger icon, it doesn't transform into a cross as intended. Even though I can see that the class .active is being added in the DOM, the menu doesn't respond to the ...

How can I arrange images vertically instead of placing them side by side?

I need help figuring out how to display multiple images in a vertical format instead of horizontally in the code below. The images are wide and take up too much space if shown side by side. My coding skills are basic, so specific guidance on where to mak ...

Is there a way to position text at the bottom of a card?

Looking to showcase multiple articles on a single page? I utilized Bootstrap 5 cards to create a visually appealing layout. While everything turned out as I hoped, the only issue I'm facing is that the "read more" link is not positioned at the bottom ...

Eliminating empty space within my container

I am facing an issue with a container that contains an image and a button on top of it. There seems to be some extra space created within the container on the right side which is taking up more space than necessary. The layout consists of three horizontal ...

What is the best way to eliminate the appearance of the blue square that shows up when the button is clicked on smaller screens?

When testing my project on different screen sizes in Chrome dev tools or on my phone, I noticed a blue square briefly appearing around the button when it is clicked. I attempted to remove this by setting outline: none or outline: 0 on various pseudo-classe ...

Unusual JavaScript Bug: Uncaught TypeError - Unable to access property 'url' of null

I encountered a peculiar JavaScript error. The following message appears in the console: Uncaught TypeError: Cannot read property 'url' of null (Line 83) The code on Line 83 looks like this: var image = '<img class="news_image_options ...

What is the best method to style a child input element's placeholder using Tailwind CSS?

I'm currently working on a project and trying to translate a CSS style that targets the ::placeholder pseudo-element into Tailwind CSS. However, I have encountered some challenges during this process as I'm not entirely sure of the correct approa ...

Exploring Navigation States with JQuery: Active, Hover, and Inactive

I've been struggling with the code below as it doesn't seem to be working. I had a simpler code before for swapping images, so if there's an easier way to achieve this, I'm open to suggestions. Just to recap, I'm trying to: 1. La ...

What could be the reason for my Node.js Express response coming back as empty?

While working on a registration system, I have encountered an issue. When errors occur in the form, I receive the correct error messages. However, when a user with the same email attempts to register and triggers 'res.json({error: 'email exists& ...

Utilizing JavaScript to enable HTML checkbox to be checked automatically

I am currently working on a constructor that generates checkboxes within a loop. My issue lies in attempting to set these checkboxes as checked, however, it doesn't seem to be functioning correctly. Below is the code snippet: funct ...

Retrieving Basic HTML Source Code in UITextView Without CSS Styling Using Objective-C

I am looking to make changes to HTML text within a UITextView. The original text was created using an HTML editor in the web version of the app and needs to be edited with a default font on iOS. Here is the simple HTML code for the text that needs editing ...

Combining all elements of my application into a single HTML, JS, and CSS file

My AngularJS app has a specific structure that includes different directories for each component: theprojectroot |- src | |- app | | |- index.html | | |- index.js | | |- userhome | | | |- userhome.html | | | ...

Guide to altering the characteristics of a button

Here is the code for a button within My Template: <div *ngFor="let detail of details" class = "col-sm-12"> <div class="pic col-sm-1"> <img height="60" width="60" [src]='detail.image'> </div> <div ...

Troubles with modal functionality in Ionic application involving ion-slide-box

Utilizing ion-slider to display images has been a seamless experience, except for one hiccup. If I navigate directly from the first full image back to the home screen, the slider ceases to function properly. To address this challenge, I have employed spec ...

Tips for displaying real-time error notifications from server-side validation using AJAX

Seeking a way to display inline error messages from my Symfony2 Backend without refreshing the page. I considered replacing the current form in the HTML with the validated form containing the error messages returned by the backend through AJAX. However, ...

Adding a dynamic form to each row in a table: A step-by-step guide

https://i.sstatic.net/HctnU.jpg Hey there! I'm facing a challenge with dynamically generated rows in a form. I want to send only the inputs from the selected row when a checkbox is clicked. Can you help me figure this out? I tried using let rowForm ...

What is the best way to save high-resolution images created with HTML5 canvas?

Currently, there is a JavaScript script being used to load and manipulate images using the fabricjs library. The canvas dimensions are set to 600x350 pixels. When smaller images are uploaded onto the canvas and saved as a file on disk, everything works c ...

Leveraging Firebase Dynamic Links through JavaScript

Currently exploring options for implementing Dynamic Links. Firebase Dynamic Links seem promising, but the lack of support for Cordova/ ionic apps is concerning. Is there any plan to add this in the future? Are there any other alternatives that you would ...

Ways to trigger a modal programmatically in the backend code?

My goal is to trigger the display of a modal when a button is clicked. The modal should be shown by clicking this button: <asp:Button ID="Button4" runat="server" class="btn btn-info" data-toggle="modal" OnClientClick="return false;" data-target="#View1 ...

What is causing the malfunction with this JQuery/AJAX request?

Currently in the process of setting up an autocomplete feature. Following the guidance from php academy at the moment. My goal is to display "suggestions go here" below the input field whenever something is typed in. I have two files for this task: home.ph ...