How to Change Background Colors on OnClick


The onClick HTML event attribute is a designator for an action to be taken when the Web page element that it is attached to is clicked with the mouse. Its natural interaction with JavaScript allows you to take many different types of actions with the attribute, including actions that effect elements of the Web page other than the one being clicked. With an onClick event, a task like changing the background color of a Web page becomes a simple one.

  • Open the Web page with the background color you wish to change in your preferred text editor.

  • Insert the following code in the <head> section of your Web page:

    <script language="JavaScript">


    function changeBackgroundColor(color){

    document.bgColor = color;




  • Insert the following code in the tag of the element that you want to trigger the background color change:


    Substitute the hexadecimal value of your desired color for #000099.

  • Save and publish your Web page. Its background will now change to your desired color when the element you specified is clicked with the mouse.


  • Photo Credit Stockbyte/Stockbyte/Getty Images
Promoted By Zergnet


Read Article

Geek Vs Geek: Robot battles, hoverboard drag race, and more

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!