Javascript set background image

How to Change Background Image in Javascript

In this tutorial, you will learn how to change background image in javascript. Images play a very important role in making your website more attractive to users. You must have seen a lot of websites where they use either some sort of background color or background image to match the theme of their website.

The background image can be added using CSS. But to change it dynamically, we have to make use of javascript. This is something which we are going to cover today. The background image is generally applied to the body element.

To set or change background image of any element, you can make use of the backgroundImage property. We are going to use this property to accomplish our goal.

In the following example, we have multiple images in the images directory. We also have 4 button elements. Upon click of each button, we will pick one image from the images directory and set it as our background image. Please have a look over the code example and the steps given below.

  • We have 2 elements in the HTML file ( div and button ). The div element is just a wrapper for the button elements.
  • The background.jpg is our default background image for the body element.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
  • We have selected all the button elements using the document.querySelector() method and stored them in the btn1 , btn2 , btn3 , and btn4 variables respectively.
  • We have attached the click event listener to all the button elements.
  • In the click event handler function of each button element, we are using the backbgroundImage property of the body element to replace the background image with one of the images present in the images directory.
  • In the case of the 4th click event handler function, we are not picking an image from the images directory using relative URL rather we are using an absolute URL. The browser will load the image from that absolute URL and then set it as our background image.
let btn1 = document.querySelector('#btn-1'); let btn2 = document.querySelector('#btn-2'); let btn3 = document.querySelector('#btn-3'); let btn4 = document.querySelector('#btn-4'); btn1.addEventListener('click', () =>< document.body.style.backgroundImage = "url('images/1.jpg')"; >); btn2.addEventListener('click', () =>< document.body.style.backgroundImage = "url('images/2.jpg')"; >); btn3.addEventListener('click', () =>< document.body.style.backgroundImage = "url('images/3.jpg')"; >); btn4.addEventListener('click', () =>< document.body.style.backgroundImage = "url('https://i.imgur.com/mPKfD2J.jpg')"; >);

Источник

Читайте также:  Java for playing games

Style backgroundImage Property

The backgroundImage property sets or returns the background image of an element.

Tip: In addition to the background-image you should also specify a background-color. The background-color will be used if the image is unavailable.

See Also:

Syntax

Return the backgroundImage property:

Set the backgroundImage property:

Property Values

Value Description
url(‘URL’) The location of the image file
none No background image. This is default
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

Technical Details

Browser Support

backgroundImage is a CSS1 (1996) feature.

It is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

More Examples

Example

Set a background image of a specific element:

Example

Return the background image of a specific element:

Example

Return the background image of a document:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

JavaScript: change a webpage background image tutorial

When you want to change a webpage background image using JavaScript, you can do so by setting the background image of the document object model (DOM) property.

The property you need to manipulate for changing the background image of the whole page is document.body.style.backgroundImage :

You need to put the relative path to the image from your web page’s folder. If the image is located in the same folder, then you can reference it directly inside the url() function as in the code above.

When the image is one folder down, add the correct relative path as follows:

Or go up one folder with the following relative path:
If you have the image URL available publicly on the internet, you can pass the full url into the property as in the following example:
 The code above will change the background image into an image that I have created for my website. You can test the code out by changing the image of Google’s homepage. First, open your browser’s developer console. Then in the Console tab next to Elements tab, write the following code:
The background image of Google’s homepage will change to the specified image, just like in the screenshot below:

Changing the background image of Google

By default, the image you selected as a background will be repeated to cover the whole page. You may want to style the background image further by setting the background-repeat style to «no-repeat» and the background-size style to «cover» .

To add the extra styles using JavaScript, you need to set the style property, which contains the same styling property but with a camelCase instead of kebab-case . For example, background-repeat becomes backgroundRepeat :

Inside your web application, you may want to trigger the background image change when the visitors do something. For example, you can change the background image when a is clicked:

If you want to wait until the page and the resources are fully loaded, you can listen for the load event instead:

The document.body code means you are selecting the tag of your HTML page. You can also change only a part of your page by selecting only that specific element.

  • getElementById() — get a single element with matching id attribute
  • getElementsByClassName() — get elements with matching class attribute
  • getElementsByName() — get elements with matching name attribute
  • getElementsByTagName() — get elements with matching tag name like «li» for
  • , «body» for

The most recommended approach is to use getElementById() because it’s the most specific of these methods. Out of the four methods, only getElementById() will retrieve a single element.

The following example shows how you can change the background of element with id=»user» attribute:

 And that’s how you change the background image of a webpage using JavaScript 😉

Learn JavaScript for Beginners 🔥

Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.

A practical and fun way to learn JavaScript and build an application using Node.js.

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

Set Background Image of a Div via Function in JavaScript

In the process of making attractive and responsive websites stand out, there is a requirement to add images to the Document Object Model(DOM) upon triggering the functionalities. This eventually leads to making the user stay on the site and explore it, which results in increased traffic in favor of the developer. In such case scenarios, setting the background image of a div via JavaScript functions does wonder in providing added functionalities.

This article will explain the approaches to set the background image of a div via a function in JavaScript.

How to Set the Background Image of a Div via Function in JavaScript?

The background image of a div via a function in JavaScript can be set by using the following approaches:

Approach 1: Set the Background Image of a Div With the Help of a Function in JavaScript Using the style.backgroundImage Property

The “backgroundImage” property returns the element’s background image. This property can be utilized to fetch the “div” element with the help of a user-defined function and apply a background image to it.

  • url” refers to the image file’s location.
  • back” points to the background image.
  • initial” refers to the property’s default value.
  • inherit” indicates the inheritance of the property from its parent element.

Example
Let’s follow the below-given example:

In the above code snippet, perform the following steps:

  • Include the “div” element with the specified “id” and adjusted dimensions.
  • After that, include the stated heading.
  • Also, create a button with an attached “onclick” event redirecting to the function divBackground().

Let’s move to the JavaScript part of the code:

< script >
function divBackground ( ) {
document. getElementById ( «head» ) . style . backgroundImage = ‘url(«template3.PNG»)’ ;
}

In the above code snippet:

  • Declare a function named “divBackground()”.
  • In its definition, access the included “div” element by its “id” using the “document.getElementById()” method.
  • Lastly, apply the “style.backgroundImage” property with the specified image’s location as “url”.
  • This will result in setting the background image to the included heading and button in the “div”.

In the above output, it is evident that the background image is applied to the contained “heading” and “button” within the “div”.

Approach 2: Set Background Image of a Div via Function in JavaScript Using setAttribute() Method

The “setAttribute()” method sets a new value to an attribute. This method can be applied to set the attribute as a “background image” to the contained table in the “div” element.

  • name” refers to the attribute’s name.
  • value” points to the attribute’s value.

Example
Let’s have a look at the following lines of code:

In the above code snippet:

  • Include the “div” element with the specified “id”.
  • Also, contain the stated “table” within the “div” with the specified values of “table-header” and “table-data”.
  • In the next step, create a button with an attached “onclick” event invoking the function backgroundImage().

Let’s continue to the JavaScript part of the code:

< script type = "text/javascript" >
function backgroundImage ( ) {
document. getElementById ( ‘head’ ) . setAttribute ( «style» , «background-image: url(‘template3.PNG’)» )
}

In the above code snippet, perform the following steps:

  • Declare a function named “backgroundImage()”.
  • In its definition, access the “div” element by its “id” using the “document.getElementById()” method.
  • After that, apply the “setAttribute()” method with the specified image’s path as discussed and the “style” attribute as its parameter.

From the above output, it can be observed that the background image is added to the table upon the button click.

Conclusion

The “style.backgroundImage” property or the “setAttribute()” method can be utilized to set the background image of a div via function in JavaScript. The former approach can be implemented to fetch the “div” element with the help of a user-defined function and apply a background image to it. The latter method can be utilized to set the background image of the included table by setting its (image) attributes. This tutorial explains how to set the background image of a div with the help of a function using JavaScript.

About the author

Umar Hassan

I am a Front-End Web Developer. Being a technical author, I try to learn new things and adapt with them every day. I am passionate to write about evolving software tools and technologies and make it understandable for the end-user.

Источник

Оцените статью