How to Change Background Colors on OnClick

  • Print this article
Change the background color of a Web page with a mouse click.
Change the background color of a Web page with a mouse click.

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.

Instructions

    • 1

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

    • 2

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

      <script language="JavaScript">

      <!--

      function changeBackgroundColor(color){

      document.bgColor = color;

      }

      //-->

      </script>

    • 3

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

      onClick="javascript:changeBackgroundColor('#000099')

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

    • 4

      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.

Related Searches

References

  • Photo Credit Stockbyte/Stockbyte/Getty Images

Comments

You May Also Like

Related Ads

Featured
View Mobile Site