Add random CSS classes to a paragraph in JavaScript

By: Ajdin Imsirovic 10 January 2021

In this interesting exercise, we’ll use a JS array and pick out its members randomly, then use setInterval to update CSS classes with these random array members every second. It results in a nice “class rotator”.

Umbrellas various colors

For this task, we’ll start with a boilerplate HTML page with Bootstrap 4 styles from a CDN and a paragraph with an id so that we can hook into it easily. We’ll then add random CSS classes from an array of CSS classes.

Here’s our code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<!DOCTYPE html>
<html>
<head>
  <link 
    rel="stylesheet" 
    href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" 
    integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" 
    crossorigin="anonymous">
</head>
<body>
  <p id="theParagraph">Lorem ipsum.</p>
  <script>
    let classesArr = [
        'lead',
        'bg-success',
        'border border-danger',
        'btn btn-danger',
        'm-5',
        'display-1',
        'text-secondary',
        'display-2'
    ];
    function addRandomClasses(){
        let p = document.getElementById('theParagraph');
        
        p.setAttribute('class', '');

        let randomSelection = 
            classesArr[ Math.ceil(Math.random()*classesArr.length - 1) ];
        console.log(randomSelection);
        p.setAttribute('class', randomSelection);
    };
    setInterval(function(){ addRandomClasses() }, 1000);

  </script>  
</body>
</html>

The code above should be easy to understand.

Here’s how it works:

  1. We start the script by assigning an array of Bootstrap 4’s built-in CSS classes to the classesArr.
  2. We then define the addRandomClasses() function; this function will be used as a callback function when we run the setInterval() facade function
  3. In our setInterval() invocation, we simply provide the addRandomClasses() function as a callback, then provide it the second argument of 1000 milliseconds, which is the amount of time that setInterval() should wait before it invokes the callback function again.

So basically, every second, we reset the class attribute’s value, and then add a random class by passing the addRandomClasses to the setInterval() method.

The live example can be found here.



Note:
This exercise comes from Book 3 of my book series on JS, available on Leanpub.com.



Feel free to check out my work here: