9

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?

Manish Shrivastava
  • 30,617
  • 13
  • 97
  • 101
arden
  • 125
  • 1
  • 9

1 Answers1

13

You can use jquery prototype to do this:

$.fn.setBgColor = function($color) {
    return $(this).css("background-color", $color);
}
$(".bg-red").setBgColor("red");
Radonirina Maminiaina
  • 6,958
  • 4
  • 33
  • 60
  • @user4448631 you should click "correct" for this answer. ;) – Manish Shrivastava May 08 '15 at 07:44
  • it says i must wait for another 4 minutes – arden May 08 '15 at 07:47
  • 2
    I think that, within jQuery prototype, you do not need `$(this)`, but just `this`. Also, this could be made more similar to other jQuery function, by doing `$.fn.bgcolor = function(color) { return (typeof color == 'undefined') ? this.css('background-color') : this.css('background-color', color); }` – Matteo Tassinari May 08 '15 at 10:01