July 29, 2014

How to change background color using Javascript?

How to change background color using Javascript

You can allow your website viewers to choose the theme of your website they like. This is done by changing the background color or background image or text color easily using JavaScript by clicking on a button.

When the button is clicked the JavaScript changes the stylesheet.

HTML

<body id="theme" class="black">
    <input type="button" value="Green" onclick="greenColor1()" class="button green" />
    <input type="button" value="Blue" onclick="blueColor1()" class="button blue" />
</body>

CSS

.blue { background-color:blue; }

.green { background-color:green; }

.black { background-color:black; }

.button { padding: 10px 30px; color: #fff; font-size: 20px; border: 1px solid #fff; border-radius: 5px; cursor: pointer }

JavaScript

var divName = "theme";

    var greenColor = "green";
    var blueColor = "blue";

    function greenColor1() {
        var divReference = document.getElementById(divName);
        divReference.className = greenColor;
    }

    function blueColor1() {
        var divReference = document.getElementById(divName);
        divReference.className = blueColor;
}
Demo

No comments:

Post a Comment

Popular Posts

Views