Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript custom method

I have created a custom object and added a method to it which is called changeColor with an attribute. The idea is when I attach this method to any DOM element that elements all content color must change.

Here is my started code:

function CustomColor() {

}

CustomColor.prototype.changeColor = function(color){
   //here what I have to specify.

}

This is pretty basic but I am new to JavaScript. Thanks.

like image 729
naresh kumar Avatar asked Oct 22 '25 14:10

naresh kumar


1 Answers

use CustomColor like this:

function CustomColor(element) {
    this.element = element;
}
CustomColor.prototype.changeColor = function (color) {
    this.element.style.color = color;
}

new instance of CustomColor:

var element = new CustomColor(document.body);
element.changeColor('red');

you can also extend the actual dom element without using any extra classes like this:

Element.prototype.changeColor = function (color) {
    this.style.color = color;
};

and use it like this:

document.body.changeColor('red')
like image 84
Shlomi Komemi Avatar answered Oct 25 '25 05:10

Shlomi Komemi