Generating a Random CSS Class in JavaScript with Math.random() Function

I'm currently enrolled in a Basic HTML/Javascript course and I'm struggling with how to "modify the following JavaScript so that it picks one of the style classes at random each time it is called." The code provided below is functional, but lacks randomization. I would appreciate any suggestions or assistance. Thank you in advance!

<html>

<head>
<title>HTML and JavaScript</title>
<link href="capstone.css" rel="stylesheet" type="text/css"></link>
<script>
function getRandomInt (min, max) 
{
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
var index = getRandomInt(1, 20);

function stylize()
{
  index++;
  if (index > 7) index =1;
  var s = "myStyle" + index;
  var e = document.getElementById("MessageText");
  e.className = s;
  setTimeout("stylize()", 1500);
  return;
}
 </script>
 </head>

 <body onLoad="stylize()">
  <table align="center" border="1" bordercolor="black">
   <tr>
    <td align="center">
     <font size="3"><b>STYLE CLASS VIEWER</b></font>
    </td>
   </tr>
   <tr>
    <td align="center" height="100" width="400">
     <div id="MessageText" class="myStyle1">
      Hello World Wide Web!
     <div>
    </td>
   </tr>
  </table>
 </body>

</html>

MY CSS PAGE IS:.....

.myStyle1 {font-family:Impact; color:black; font-size:100}
.myStyle2 {font-family:Georgia; color:black; font-size:18}
.myStyle3 {font-family:Tahoma; color:black; font-size:24}
.myStyle4 {font-family:Verdana; color:black; font-size:48}
.myStyle5 {font-family:Impact; color:red; font-size:30}
.myStyle6 {font-family:Marlett; color:green; font-size:65}
.myStyle7 {font-family:Arial; color:blue; font-size:46}
.myStyle8 {font-family:Courier Sans MS Bold; color:blue; font-size:60}
.myStyle9 {font-family:Impact; color:blue; font-size:35}
.myStyle10 {font-family:Arial Italic; color:blue; font-size:10}
.myStyle11 {font-family:Times New Roman; color:blue; font-size:50}
.myStyle12 {font-family:Tahoma; color:blue; font-size:38}
.myStyle13 {font-family:Verdana; color:white; font-size:30}
.myStyle14 {font-family:Marlett; color:blue; font-size:70}
.myStyle15 {font-family:Impact; color:blue; font-size:24}
.myStyle16 {font-family:Georgia; color:blue; font-size:24}
.myStyle17 {font-family:Impact; color:blue; font-size:35}
.myStyle18 {font-family:Georgia; color:black; font-size:12;}
.myStyle19 {font-family:Arial; color:blue; font-size:20;}
.myStyle20 {font-family:Tahoma; color:blue; font-size:55}

This implementation doesn't seem to work for me. Can anyone provide assistance?

Answer №1

Replace the line var index = getRandomInt(1, 20); with a new line of code.

Update the line index++; to var index = getRandomInt(1, 20); for better functionality.

If you wish to allow more than 7 styles, eliminate the line if (index > 7) index = 1;.

In this scenario, a random number will be selected each time. Previously, a random number was chosen (typically 1 from if (index > 7) index = 1;) and then incremented.

<html>

<head>
<title>HTML and JavaScript</title>
<link href="capstone.css" rel="stylesheet" type="text/css"></link>
<style>
 .myStyle1 {font-family:Impact; color:black; font-size:100} .myStyle2 {font-family:Georgia; color:black; font-size:18} .myStyl31
{font-family:Tahoma; color:black; font-size:24} .myStyle4 {font-family:Verdana; color:black; font-size:48} .myStyle5 {font-family:Impact;
color:red; font-size:30} .myStyle6 {font-family:Marlett; color:green; font-size:65} .myStyle7 {font-family:Arial; color:blue;
font-size:46} .myStyle8 {font-family:Courier Sans MS Bold; color:blue; font-size:60} .myStyle9 {font-family:Impact; color:blue;
font-size:35} .myStyle10 {font-family:Arial Italic; color:blue; font-size:10} .myStyle11 {font-family:Times New Roman; color:blue;
font-size:50} .myStyle12 {font-family:Tahoma; color:blue; font-size:38} .myStyle13 {font-family:Verdana; color:white; font-size:30}
.myStyle14 {font-family:Marlett; color:blue; font-size:70} .myStyle15 {font-family:Impact; color:blue; font-size:24} .myStyle16
{font-family:Georgia; color:blue; font-size:24} .myStyle17 {font-family:Impact; color:blue; font-size:35} .myStyle18 {font-family:Georgia;
color:black; font-size:12;} .myStyle19 {font-family:Arial; color:blue; font-size:20;} .myStyle20 {font-family:Tahoma; color:blue;
font-size:55}
</style>
<script>
  function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
  

  function stylize() {
    var index = getRandomInt(1, 20);
    var s = "myStyle" + index;
    var e = document.getElementById("MessageText");
    e.className = s;
    setTimeout("stylize()", 1500);
    return;
  }
</script>
 </head>

 <body onLoad="stylize()">
  <table align="center" border="1" bordercolor="black">
   <tr>
    <td align="center">
     <font size="3"><b>STYLE CLASS VIEWER</b></font>
    </td>
   </tr>
   <tr>
    <td align="center" height="100" width="400">
     <div id="MessageText" class="myStyle1">
      Hello World Wide Web!
     <div>
    </td>
   </tr>
  </table>

 </body>

</html>

Answer №2

Important Note

Here is a more concise version of the code:

var text = document.getElementById("text");

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function stylize() {
  var interval = setInterval(function() {
    var rand = getRandomInt(1, 20);
    text.setAttribute("class", "myStyle" + rand);
  }, 1500);
}

stylize();
.myStyle1 {
  font-family: Impact;
  color: black;
  font-size: 100
}

.myStyle2 {
  font-family: Georgia;
  color: black;
  font-size: 18
}

... (remaining styles omitted for brevity)
<table align="center" border="1" bordercolor="black">
  <tr>
    <td align="center">
      <font size="3"><b>STYLE CLASS VIEWER</b></font>
    </td>
  </tr>
  <tr>
    <td align="center" height="100" width="400">
      <div id="text" class="myStyle1">
        Hello World Wide Web!
      </div>
    </td>
  </tr>
</table>

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

Discover the steps to convert an image to base64 while circumventing the restrictions of the same-origin policy

I've been struggling to convert an image link to base64 in order to store it on the client-side browser (IndexedDB). Despite searching for a solution for days, I have not been able to find one that addresses my issue. While I can successfully convert ...

html - Removing excess space following the footer

Having trouble getting rid of the excess white space below my footer on this website: I attempted to search for a solution online and even added padding:0; to the footer's CSS, but unfortunately it didn't solve the issue. Appreciate any assista ...

Display loading spinner and lock the page while a request is being processed via AJAX

Currently, I am working on a project using MVC in C#, along with Bootstrap and FontAwesome. The main objective of my project is to display a spinner and disable the page while waiting for an ajax request. Up until now, I have been able to achieve this go ...

Switch on the warning signal using bootstrap

How can I make the alert below toggle after 2 seconds? <div class="alert alert-info"> <a href="#" class="close" data-dismiss="alert">&times;</a> Data was saved. </div> ...

Struggling to properly close the bootstrap tags

Having an issue where I can't seem to properly close Bootstrap tags in my code. Here's a snippet of the HTML: <html> <head> <link href="css/bootstrap.min.css" rel="stylesheet"> <script src="js/jquery.js ...

Links have a longer transition delay compared to the content

In a unique JavaScript function I've developed, the my-content-section-visible class is removed and replaced with my-content-section-hidden. This change is being made to hide a particular div using a smooth transition effect. The transition itself is ...

The functionality of Selenium's get(link) feature appears to be experiencing issues

Recently, I wrote a simple piece of code using selenium to open a webpage. from time import sleep from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By import warnings warnings.simp ...

Inconsistency in css asset URLs across various pages discovered while working with Rails

When using assets stylesheet to load a CSS file, I noticed that it only loads on the index page. Upon inspecting with F12, the console shows the URL for other pages as well, which appends "/cloths" to the asset path. I am currently utilizing the default la ...

I am unable to activate Wicket's onchange event

I've been trying to automate the population of three dropdown selection elements using a Chrome extension. I'm able to change the value of the first dropdown, but it doesn't trigger the necessary action that populates the second and third dr ...

CSS ISSUE: Issue with hidden overflow causing white space next to border in nested divs

When working with a div inside another div and setting overflow to hidden, you may notice a whitespace issue around the border when zooming in and out on Chrome. Firefox handles this situation better, showing white space only in the corners of the border. ...

Link-defying button

I'm developing a website with a homepage that serves as an entry point to the rest of the site (it welcomes the user and allows them to click anywhere to access the main website). The following code accomplishes this: <template> <div onc ...

Leverage an HTML table to serve as a data source for populating a Kendo UI template

My latest creation is a unique service that generates HTML tables based on request parameters. The current implementation returns the data as an HTML page in string format. Here's a sample output: <!DOCTYPE html> <html> <head> ...

The new version 5.1 of Bootstrap modal does not disable scrolling on the <body> element

I'm currently working on a project in Angular 11 using Bootstrap (v5.1.3). My main goal is to create a functionality where clicking on a card, similar to a blog post, will trigger a Bootstrap modal popup displaying the content of that specific post. B ...

I am experiencing an issue where my application, built using NodeJS, Express, and Javascript, is failing to insert form data into the database despite

I am facing a challenge with my app's MVC design pattern where I am unable to insert form information into the corresponding table in the database. Despite installing the body-parser package via npm, the form is not functioning as expected. Can anyone ...

Is the presence of a 'disabled' attribute on a non-input element enough to render your document invalid in HTML?

Originally intended for <input/> elements, the disabled attribute raises a question when applied to non-input elements. Could this potentially lead to document invalidation? ...

Adjust the default margins and padding of email header images specifically for Outlook emails

I am currently working on coding an email, and I have encountered an issue with the alignment of the hero image, specifically in Outlook. https://i.sstatic.net/ap7SG.png Despite trying various solutions from previous answers to this problem (such as sett ...

Resolve a container overflow problem within the footer section

Trying to adjust the footer (newsletter signup form) on this page to fall to the bottom of the page has been a challenge. The #container element appears to be larger than the body, causing layout issues. Any suggestions on how to resolve this? An image d ...

A floating transparent Turing image transformed into a clickable image

After creating an image button with a transparent black hover effect, I noticed that the image no longer functions as a "button." However, the hover effect still works. Is there a way to maintain the button functionality while keeping the color overlay? V ...

Error: The database connection is currently down

Hey there! I'm currently working on a school project and running into some issues with inserting data into the database. I can't figure out what I'm doing wrong. There are no errors showing up, but for some reason, the information I input i ...

Tips on expanding the space between words in a scrolling "marquee" text

Looking for some assistance with my jQuery project involving a horizontal scrolling "marquee" text. I am currently trying to adjust the size of the gap between the phrases in the marquee. Here is an example with the phrase "HEY THERE". jQuery(document ...