0

Currently on my style sheet I have the following:

a {
box-shadow: inset 0 -1.3vw 0 0 #AFFFFF;
}

This creates a fake custom underline.

I want it so that every time the page is loaded or refreshed the color of the border changes to a random color specified in the array.

I found this script here a little while ago:

var colors = ['#ff0000', '#00ff00', '#0000ff'];
var random_color = colors[Math.floor(Math.random() * colors.length)];
document.getElementById('title').style.color = random_color;

How do I go about doing this the right way?

0

3 Answers 3

2

In your example you are using javascript to set the text colour every time that script is executed. You can simply change it to set the boxshadow every time instead.

Note: css properties with a hyphen (-) in are converted to camelCase; box-shadow becomes boxShadow

var colors = ['#ff0000', '#00ff00', '#0000ff'];
var random_color = colors[Math.floor(Math.random() * colors.length)];
document.getElementById('title').style.boxShadow = "inset 0 -1.3vw 0 0 "+random_color;
a {
    box-shadow: inset 0 -1.3vw 0 0 #AFFFFF;
}
<a id="title">test</a>

Sign up to request clarification or add additional context in comments.

Comments

2

You could just add a random class to the element, with the classes associated with different colors:

CSS:

a.red {
    box-shadow: inset 0 -1.3vw 0 0 red;
}
a.blue {
    box-shadow: inset 0 -1.3fw 0 0 blue;
}
a.yellow {
    box-shadow: inset 0 -1.3fw 0 0 yellow;
}

And your JS:

var classes = ['red', 'blue', 'yellow'];
var random_class = classes[Math.floor(Math.random() * classes.length)];
var title = document.getElementById('title');
classes.forEach((el) => {
   title.classList.remove(el);
});
title.classList.add(random_class);

Comments

0

I wouldn't use styles this way. I would predefine classes in CSS file and assign those classes to elements.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.