How to change background color using javascript and keep it?

I am new to javascript and here is my html and javascript code. (Omitted some part of html for brevity).

<form action="">
        <button onclick="changeColor('blue')">Make Blue</button>
        <button onclick="changeColor('red')">Make Red</button>
</form>

Here is my javascript code:

function changeColor(color) {
    document.body.style.backgroundColor = color;
}

When I open my html file, I have two buttons, but when I click it, the background changes only for a second to either red or blue depending on which button I’ve pressed and then goes back being white. How do I make it so that the color stays red and will only change if I hit blue button again?

Thanks

Hi,

The reason you are seeing a flash of color is that the JavaScript is kicking, then the form is submitting, causing a page refresh.

To solve this, just lose the form :slight_smile:

<button onclick="changeColor('blue')">Make Blue</button>
<button onclick="changeColor('red')">Make Red</button>
1 Like

Thank you so much.

1 Like

perfect answer. i have used this code for one of my client’s site and its working for me. try this

if you also added a cookie into the mix it could remember the last color selected and on the next visit and/or page you can retain the colour they selected. Additionally you could even change stylesheets and have a completely different look selected by the user.

Just a thought…

1 Like

Good point. I actually wrote an article on that a few years ago.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.