I want to make a function that change css property of an object. I tried code below
function setBgColor($obj, $color) {
$obj.css("background-color", $color);
}
setBgColor($(".bg-red"), "red");
and it works. but I would like to to make the function to be called from an object like this
function setBgColor($color) {
$(this).css("background-color", $color);
}
$(".bg-red").setBgColor("red");
Can someone help?
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. You can try to run the following code to learn how to change background color using jQuery:
You can also trigger the color change when a <button> element is clicked by using the .click () event handler method from jQuery. The click () method will execute the function you passed into it when the selected element is clicked.
To set the background color using jQuery, use the jQuery css () property. We will set background color on mouse hover with the jQuery on () method.
jQuery - css () Method 1 jQuery css () Method. The css () method sets or returns one or more style properties for the selected elements. 2 Return a CSS Property 3 Set a CSS Property 4 Set Multiple CSS Properties 5 jQuery Exercises 6 jQuery CSS Reference. For a complete overview of all jQuery CSS methods, please go to our jQuery HTML/CSS Reference.
You can use jquery prototype to do this:
$.fn.setBgColor = function($color) {
return $(this).css("background-color", $color);
}
$(".bg-red").setBgColor("red");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With