Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to change the background image using jQuery?
To change the background image using jQuery, use the jQuery css() method. The background-image CSS property is used to change background image.
Syntax
The basic syntax to change background image using jQuery is ?
$(selector).css("background-image", "url('path/to/image.jpg')");
Example
You can try to run the following code to learn how to change background image using jQuery ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
body {
height: 100vh;
background-color: #f0f0f0;
transition: background-image 0.3s ease;
}
p {
text-align: center;
padding: 50px;
font-size: 18px;
background-color: rgba(255, 255, 255, 0.8);
margin: 20px;
border-radius: 5px;
}
</style>
<script>
$(document).ready(function(){
$("body").on({
mouseenter: function(){
$(this).css("background-image", "url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZGVmcz48cGF0dGVybiBpZD0iZ3JhZGllbnQiIHBhdHRlcm5Vbml0cz0idXNlclNwYWNlT25Vc2UiIHdpZHRoPSIxMDAiIGhlaWdodD0iMTAwIj48cmVjdCB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIgZmlsbD0iIzRhOTBlMiIvPjxyZWN0IHdpZHRoPSI1MCIgaGVpZ2h0PSI1MCIgZmlsbD0iIzM1N2FiZCIvPjxyZWN0IHg9IjUwIiB5PSI1MCIgd2lkdGg9IjUwIiBoZWlnaHQ9IjUwIiBmaWxsPSIjMzU3YWJkIi8+PC9wYXR0ZXJuPjwvZGVmcz48cmVjdCB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIgZmlsbD0idXJsKCNncmFkaWVudCkiLz48L3N2Zz4=')");
},
mouseleave: function(){
$(this).css("background-image", "none");
}
});
});
</script>
</head>
<body>
<p>Move the mouse pointer on the page to change the background image. Move away to reset.</p>
</body>
</html>
In this example, we use the on() method to bind mouseenter and mouseleave events to the body element. When the mouse enters the page, a blue checkered pattern background is applied using an SVG data URL. When the mouse leaves, the background image is removed.
Conclusion
The jQuery css() method provides an easy way to dynamically change background images by modifying the background-image CSS property. This technique is useful for creating interactive visual effects on web pages.
