How to change the background color by using JQuery
Last updated:31st Jul 2022
In this article, you will change the background color of an element by using jquery. To add the background color, we will use the CSS( ) method of jquery.
CSS() method is used to retrieve and set the value of CSS properties.
syntax:$(selector).css("background-color","color-name")
for example, you have an HTML form as follows:
<!DOCTYPE html>
<html>
<body>
<h1>change background color by using jquery</h1>
<button id="btn-bg">change bg color</button>
</body>
</html>
if you want to change the background color of the body tag when the user clicks on 'change bg color',
for that use the jquery code below.
<script>
$(document).ready(function(){
$("#btn-bg").click(function(){
$("body").css("background-color","red");
});
});
</script>
when the user clicks on the 'change bg color' button, the jquery code will get executed, and the background color of the body
tag get a change to red.
let me show you one example, of how you can change the background color.
Example
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>change background color by using jquery</h1>
<button id="btn-bg">change bg color</button>
<p>click on above button</p>
<script>
$(document).ready(function(){
$("#btn-bg").click(function(){
$("body").css("background-color","red");
});
});
</script>
</body>
</html>