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
:
document.body.style.backgroundImage = "url('image.png')";
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:
document.body.style.backgroundImage = "url('./assets/image.png')";
Or go up one folder with the following relative path:
document.body.style.backgroundImage = "url('../image.png')";
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:
document.body.style.backgroundImage =
"url('https://sebhastian.com/img/default.png')";
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:
document.body.style.backgroundImage =
"url('https://sebhastian.com/img/default.png')";
The background image of Google’s homepage will change to the specified image, just like in the screenshot below:
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
:
document.body.style.backgroundRepeat = "no-repeat";
document.body.style.backgroundSize = "cover";
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 <button>
is clicked:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>JavaScript change background image</title>
<script>
// The function below will change the background image
function changeBackgroundImage() {
document.body.style.backgroundImage = "url('image.png')";
document.body.style.backgroundRepeat = "no-repeat";
document.body.style.backgroundSize = "cover";
}
</script>
</head>
<body>
<h1>Click the button to change the background image:</h1>
<button onclick="changeBackgroundImage();">Change</button>
</body>
</html>
Or you can also immediately change the background image after the page is loaded by listening to the DOMContentLoaded
event as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>JavaScript change background image</title>
<script>
// The function below will change the background image
function changeBackgroundImage() {
document.body.style.backgroundImage = "url('image.png')";
}
// call the function when the whole DOM content is loaded
document.addEventListener("DOMContentLoaded", changeBackgroundImage());
</script>
</head>
<body>
<h1>Change the background image on load</h1>
</body>
</html>
The DOMContentLoaded
event is triggered when your whole HTML page has been loaded, even though some external JavaScript, CSS, and image resources are not yet fully loaded.
If you want to wait until the page and the resources are fully loaded, you can listen for the load
event instead:
document.addEventListener("load", changeBackgroundImage());
Changing the background image of a specific element
The document.body
code means you are selecting the <body>
tag of your HTML page. You can also change only a part of your page by selecting only that specific element.
The browser provides you with several ways to select a specific element:
getElementById()
— get a single element with matchingid
attributegetElementsByClassName()
— get elements with matchingclass
attributegetElementsByName()
— get elements with matchingname
attributegetElementsByTagName()
— get elements with matching tag name like"li"
for<li>
,"body"
for<body>
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 <div>
element with id="user"
attribute:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>JavaScript change background image</title>
<script>
// change the background image of div user
function changeBackgroundUser() {
document.getElementById("user").style.backgroundImage =
"url('image.png')";
}
</script>
</head>
<body>
<div id="user">
<h1>Change specific DIV background image</h1>
</div>
<div id="guest">
<h2>This element's parent DIV background won't be changed</h2>
</div>
<div id="stranger">
<h2>Neither this one</h2>
</div>
<button onclick="changeBackgroundUser();">Change BG image</button>
</body>
</html>
Finally, you can put the bgImage
as a parameter to the changeBackgroundImage()
function so that you can have buttons that change the background to different images:
<script>
// change the background image using the passed parameter
function changeBackgroundImage(bgImage) {
document.body.style.backgroundImage = "url(" + bgImage + ")";
}
</script>
<button onclick="changeBackgroundImage('image.png');">Use image.png</button>
<button onclick="changeBackgroundImage('pic.jpg');">Use pic.jpg</button>
<button onclick="changeBackgroundImage('user.png');">Use user.png</button>
And that’s how you change the background image of a webpage using 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.
HTML & CSS
- We have 2 elements in the HTML file (
div
andbutton
). Thediv
element is just a wrapper for thebutton
elements. - The
background.jpg
is our default background image for thebody
element. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div> <button id="btn-1">1</button> <button id="btn-2">2</button> <button id="btn-3">3</button> <button id="btn-4">4</button> </div> <script src="script.js"></script> </body> </html>
body { background-image: url('images/background.jpg'); background-repeat: no-repeat; background-size: cover; } div { display: flex; justify-content: center; } button { height: 50px; width: 50px; margin: 10px; }
Javascript
- We have selected all the
button
elements using thedocument.querySelector()
method and stored them in thebtn1
,btn2
,btn3
, andbtn4
variables respectively. - We have attached the
click
event listener to all thebutton
elements. - In the
click
event handler function of eachbutton
element, we are using thebackbgroundImage
property of thebody
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')"; });
Introduction to jQuery background image change
The jQuery background image change is one of the feature for to changing the background images on the web page by using the jQuery.css() method and url() function for to change the whole property values which is specified with the url() function parameter values on html page with the help of <image> tag to insert the images on the UI the same image is edited and changed like css() instead of that we called the other attributes as parameter with jQuery selector direct url is pass the image to the url() method and it is to be stored as the new variable.
Syntax of jQuery background image change
The jQuery have default methods for to create the web application with more widgets based on the application requirements. Like that background image is the most precious thing for highlighting the application with more users. So that the application view will get more number of users, like that <img> tag is used in the html page for inserting the images but when we used css tag it gets more highlighted with background-colors, widths, rotations etc.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
$(document).ready(function()
{
$("html element id").on({
$(element id).css("attributes","url()");
});
</script>
<body>
---Some html and jQuery library methods depends on the requirement---
</body>
</html>
The above codes are the basic syntax for utilising the images and edited with the css attributes for changing the image features like background-colors, widths and resolutions.
How to change background image in jQuery?
- The image feature is the pictorial representation of the web page. The jQuery library is the easy task and it can be implemented with the some animation effects based on the requirements. We can use .css() method to change the background-image of the current web page. Using the url() parameter and the function is called the specified url that is we can locate the image path on the method. By using this method we can set the background-image by the property of the element and it needs to specify the complete property value by using the url() function notation.
- We can call the JavaScript function for to execute the user functionality and its been authenticating the user datas both image and normal format datas. Sometimes the pictorial representation of the datas is to be validated in the both end, the image also dynamically change the index of the html ui tag element also varies depends upon we used and call the function on the script. When we used css it automatically calls and used the other properties like image-width, image-length, image-resolution, image-colour the length and width will calculate using pixel format more ever image is used and called only the pixel formats.
Examples of jQuery background image change
Given below are the examples of jQuery background image change:
Example #1
Code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("body").on({
mouseenter: function(){
$(this).css("background-image", "url('E://website.jpg')");
},
});
});
$(document).ready(function() {
$("button").click(function() {
var imageUrl =
"E://one.jpg";
$(".box").css("background-image", "url(" + imageUrl + ")");
});
});
</script>
<style>
.first{
height:66px;
width:67px;
padding:19px;
margin:11px;
display:inline-block;
background-color:Red;
}
.second {
width: 750px;
height: 200px;
border: 3px solid blue;
background-repeat: repeat;
background-image: url(
"E://one.jpg");
}
h1{
color:blue;
}
</style>
</head>
<body>
<center>
<h1>Welcome Users</h1>
<h3>
Welcome To My Domain its a first example
</h3>
<div class="second"></div>
<p>
<button type="button">
Thank you for using the application have a nice day users
</button>
</p>
</center>
</body>
</html>
Output:
In the above example we used two different images with the same html web page. We used button for the second image on the html web page for refreshing the page.
Example #2
Code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
var images = ["E://one.jpg"];
$(document).ready(function() {
$("#second").css("background-image", `url(${images})`)
.css("width", 1500)
.css("height", 1500).css("background-color", "violet");
})
</script>
<style>
.second {
width: 750px;
height: 200px;
border: 3px solid blue;
background-repeat: repeat;
background-image: url(
"E://one.jpg");
background-color:"violet";
}
</style>
</head>
<body>
<div id="second">
<ul>
<li><a href="#hme">Home</a></li>
<li><a href="#abtus">Aboutus</a></li>
<li><a href="#cnt">Contactus</a></li>
<li><a href="#products">Products</a></li>
<li> 1.Banian</li>
<li> 2.T-Shirts</li>
<li> 3.Pants</li>
<li><a href="#email">Email</a></li>
<li><a href="#fdback">Feedback</a></li>
</ul>
<p><marquee>Welcome To My Domain its a second example have a nice day users please try again</marquee></p>
</div>
</body>
</html>
Output:
In second example we can used background images on the separate variable it will be called on the css() method and also we used some default css method attributes like width, height etc.
Example #3
Code:
<!DOCTYPE html>r
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(window).load(function(){
$('img.third').hide();
var vars = $(window).height();
var vars1 = $(window).width();
$('#example').css({'height':vars,'width':vars1});
function demo() {
$("#example img.third").first().appendTo('#example').fadeOut(2021);
$("#example img").first().fadeIn(2021);
setTimeout(demo, 2021);
}
demo();})
$(window).resize(function(){window.location.href=window.location.href})
</script>
<style>
body, html{
margin:0;
padding:0;
color:red;
font-family: 'Arial';
font-size:1.5em
}
a{color:green; text-decoration:none}
#example
position:fixed;;
z-index:-3;
top:0;
left:0;
background-color:violet
}
#example img.third{
position:absolute;
top:2;
display:none;
width:104%;
height:105%;
z-index:-2
}
.final{
width:103%;
margin:33px auto;
margin-top:34%;
background:red; -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=75)";
background-color:rgba(255,255,255,.9);
padding:3em;
border-radius:17px
box-shadow:3px 6px 9px 0 rgba(13,13,13,.8);
text-shadow: 2px 3px 5px red
}
</style>
</head>
<body>
<div class="final">
<h1>Welcome To My Domain its a Third Example</h1>
<h2>Have a Nice day users.</h2>
<p>"To change the background image using jQuery library, use the jQuery css() method for changing the background-image CSS property is used to change the background image."<code><img></code>Replace one image with another one with the specific time intervals So, before we continue,we must need to define where your images are coming from the Images URLs it can be stored in javascript array memory location or we could choose more elegant way and simply used for the CRUD operations on the html file.</p>
<p>Thanks for using and spenting the time"</p>
<p><a href="http://www.google.com" target="result"> Click Me</a></p>
</div>
<div id="example">
<img class="third" src="E://website.jpg">
<img class="third" src="E://one.jpg">
</div>
</body>
</html>
Output:
The final example we used some animation effects like fadeIn(), fadeout() methods for displaying the images with some time. We can change the images every 2021 seconds after that the images are changed. We used hyperlink with some tag elements like “click me” once we click that it navigates to other page. But same page image is changed.
Conclusion
The jQuery library have many features for to present the web application with user friendly and it requirements. Like that images are placed on the pages with specific attributes like width, height and background-colors for specifying some pixels format to access and utilising the images on the web based application with the help of css sheets.
Recommended Articles
This is a guide to jQuery background image change. Here we discuss the introduction, how to change background image in jQuery? and examples. You may also have a look at the following articles to learn more –
- jQuery Select Option
- jQuery zindex
- jQuery width
- jQuery id Selector