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 color using jQuery?
To change the background color using jQuery, use the jQuery css() property. We will change background color on mouse hover with the jQuery on() and css() method.
Understanding jQuery css() Method
The css() method in jQuery allows you to get or set CSS properties of selected elements. To change background color, you can use css("background-color", "colorvalue") where colorvalue can be a color name, hex code, or RGB value.
Example
You can try to run the following code to learn how to change background color using jQuery ?
<!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-color", "gray");
},
mouseleave: function(){
$(this).css("background-color", "red");
},
dblclick: function(){
$(this).css("background-color", "yellow");
}
});
});
</script>
</head>
<body>
<p>Double click and move the mouse pointer to change the background color.</p>
</body>
</html>
Alternative Methods
You can also change background color using different approaches ?
// Direct color change on click
$(document).ready(function(){
$("button").click(function(){
$("body").css("background-color", "#ff6b6b");
});
});
// Using addClass() and removeClass() methods
$(document).ready(function(){
$(".color-btn").click(function(){
$("body").removeClass("red-bg blue-bg").addClass("green-bg");
});
});
Conclusion
jQuery provides multiple ways to change background colors using the css() method, event handlers like on(), or CSS class manipulation methods. These methods offer flexibility for creating interactive web pages with dynamic background color changes.
