Javascript изменить 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')"; >);

Источник

Читайте также:  Python сохранить часть строки

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:

Источник

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.

Источник

How to Change Background Image in JavaScript

In JavaScript, there are web pages that need an attractive layout, such as dark backgrounds that usually work better for interfaces. Similarly, white backgrounds let the readers focus on content, and so the news portals or blogs use a comparatively light background with dark text. In such cases, JavaScript becomes very handy in formatting and improving document design.

This article will discuss the methods to change the background image in JavaScript.

How to Change Background Image in JavaScript?

To change the background image in JavaScript, the following approaches can be utilized:

  • backgroundImage” property on “DOM”.
  • getElementById()” method and “backgroundImage” property on “paragraph”.

Go through the discussed methods one by one!

Method 1: Change Background Image in JavaScript Using backgroundImage property on DOM.

The “backgroundImage” property adjusts the background image of the specified element. This technique can be applied by applying the backgroundImage property and specifying the background image by locating its path as an argument.

In the above syntax, “URL” refers to the path of the image.

Look at the following example for demonstration.

In this example, a button will be included with the specified value and an “onclick” event redirecting to a
function named backgroundImage():

Now, a function “backgroundImage()” will be declared and the “document.body.style.backgroundImage” property will access the background image using the specified image path in its argument:

The output of the above implementation will result as follows:

Method 2: Change Background Image in JavaScript Using getElementById() method and backgroundImage property on paragraph

The “getElementById()” method returns an element with a specified value and the “backgroundImage” property, as stated above, returns the background image of the particular element specified in its argument. This method can be applied to map the specified color on the background of the particular paragraph.

Here, “elementID” refers to the id of an element.

Go through the following example for a better understanding of the stated concept.

First, include a paragraph in the

tag and assign it a specific id:

Next, create a button with an onclick event accessing the function backgroundImage() as discussed in the previous method:

Lastly, declare the function named “backgroundImage()” similarly. Here, access the defined Id using the “getElementById()” method and apply the specified background image on it. This will result in the implementation of the color on the paragraph’s background:

We have compiled the easiest method for changing background image in Javascript

Conclusion

To change background image in Javascript, apply the “backgroundImage” property on “DOM” for applying the specified background image on the whole web page using a function or by getting the particular id using “getElementById()” method and applying “backgroundImage” property on the specified “paragraph”. This blog illustrates the methods to change background images in JavaScript.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.

Источник

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