Help with random colour changing script |
Help with random colour changing script |
danieljksn |
Oct 14 2020, 02:04 PM
Post
#1
|
Group: Members Posts: 5 Joined: 14-October 20 Member No.: 27,595 |
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 |
Oct 14 2020, 02:34 PM
Post
#2
|
🌟Computer says no🌟 Group: WDG Moderators Posts: 20,730 Joined: 9-August 06 Member No.: 6 |
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. |
danieljksn |
Oct 14 2020, 03:13 PM
Post
#3
|
Group: Members Posts: 5 Joined: 14-October 20 Member No.: 27,595 |
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. 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 |
Lo-Fi Version | Time is now: 26th April 2024 - 03:59 AM |