How to Change a CSS Background Image With JavaScript

How to Change a CSS Background Image With JavaScript thumbnail
Use Javascript to change the background image.

Javascript provides dynamic, client-side code to edit your website layout. You can use Javascript to change website graphics, text, tables and even the background image. The code is used to automate dynamic background images, which is often used on blogs or online magazines to promote affiliate products. The change is invisible to website readers, and the image is shown each time the user opens the page.

Instructions

    • 1

      Open your HTML file with a simple text editor such as Notepad. You can also use more advanced text editors such as Notepad++ or Visual Studio. These editors color code sections of your HTML file for easier editing.

    • 2

      Create the Javascript block tags. All Javascript code is located in script blocks. Place these tags within the "<head>" and "</head>" tags in your HTML code:
      <script type="text/javascript"> </script>

    • 3

      Create an variable and assign it an image located on your website. The following code creates the variable and assigns it the "myImage.jpg" image:
      var background_image = "myImage.jpg";

    • 4

      Set the background image. The following code switches the default CSS background image to the variable defined in Step 3:
      document.body.background = background_image;

    • 5

      Save your changes and open the HTML in your web browser. The new changes edit the background image and display it in the browser.

Related Searches:

References

  • Photo Credit internet - eingabefeld internet http://www image by pmphoto from Fotolia.com

Comments

You May Also Like

Related Ads

Featured