CSS – Change Background Colors

Change the background colors by click on the buttons:

  • The web page represented by document in DOM (Document object model)
  • We can specify the body location using body attribute of document.
  • We can apply styles using style attribute.
  • The following program explaining how to change the background colors with button click events.
<html>
            <head>
                        <script>
                                    function blue()
                                    {
                                                document.body.style.backgroundColor=”blue”;
                                    }
                                    function green()
                                    {
                                                document.body.style.backgroundColor=”green”;
                                    }
                                    function red()
                                    {
                                                document.body.style.backgroundColor=”red”;
                                    }
                                    function yellow()
                                    {
                                                document.body.style.backgroundColor=”yellow”;
                                    }
                        </script>
            </head>
 
            <body>
                        <button onclick=”blue()”> Blue </button>
                        <button onclick=”green()”> Green </button>
                        <button onclick=”red()”> Red </button>
                        <button onclick=”yellow()”> Yellow </button>
            </body>
</html>
Scroll to Top