Printable Version of Topic

Click here to view this topic in its original format

HTMLHelp Forums _ Client-side Scripting _ Help with random colour changing script

Posted by: danieljksn Oct 14 2020, 02:04 PM

Hello all. I'm working on a very simple design that randomly loads one of three background colours for the whole document.

What I'd like to do is apply the random colour to just one div (specifically a div called "content"), so that the document itsself can have the same colour as the border. The reason is that on cell phone displays when you attempt to scroll beyond the limits of the page, the underlying colour "bleeds" behind the black border.

I didn't write the Javascript, but borrowed it from elsewhere, so don't know how to apply it to a single div rather than the whole document.

I would appreciate any help!

QUOTE
<script>
const COLORS = [
'#eefed1',
'#fefcd1',
'#fed5dc',
];

window.onload = () => {
document.body.style.backgroundColor
= COLORS[Math.floor(Math.random() * COLORS.length)];
};
</script>

Posted by: pandy Oct 14 2020, 02:34 PM

Does that DIV have the id 'content'? If so we can use that, if not give it an id.

CODE
<div id="content"> ... </div>


So now JS can access that DIV though its ID. Chance the script so it instead of document.body uses document.getElementById('content').


CODE
const COLORS = [
'#eefed1',
'#fefcd1',
'#fed5dc',
];

window.onload = () => {
document.getElementById('content').style.backgroundColor
= COLORS[Math.floor(Math.random() * COLORS.length)];
};


I confess I didn't understand the syntax of this script, with the square brackets, the = () => part and a few other things. But it works anyway. biggrin.gif

Posted by: danieljksn Oct 14 2020, 03:13 PM

QUOTE(pandy @ Oct 14 2020, 02:34 PM) *

Does that DIV have the id 'content'? If so we can use that, if not give it an id.

CODE
<div id="content"> ... </div>


So now JS can access that DIV though its ID. Chance the script so it instead of document.body uses document.getElementById('content').


CODE
const COLORS = [
'#eefed1',
'#fefcd1',
'#fed5dc',
];

window.onload = () => {
document.getElementById('content').style.backgroundColor
= COLORS[Math.floor(Math.random() * COLORS.length)];
};


I confess I didn't understand the syntax of this script, with the square brackets, the = () => part and a few other things. But it works anyway. biggrin.gif


That worked (almost) perfectly, thank you!

As is so often the case with HTML it created a new peoblem, but I think I can work it out biggrin.gif

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)