Help - Search - Members - Calendar
Full Version: Help with random colour changing script
HTMLHelp Forums > Programming > Client-side Scripting
danieljksn
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>
pandy
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
danieljksn
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
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2024 Invision Power Services, Inc.