Skip to content

Instantly share code, notes, and snippets.

@mburakerman
Last active July 28, 2023 07:07
Show Gist options
  • Save mburakerman/a33f44cdd390650e4bbe1b28f890b9d9 to your computer and use it in GitHub Desktop.
Save mburakerman/a33f44cdd390650e4bbe1b28f890b9d9 to your computer and use it in GitHub Desktop.
The simplest vanilla js plugin template
// <div id="box">Lorem</div>
// Our goal is to make text color red
var Makered = function(selector) {
this.el = document.querySelector(selector); // for multiple elements use querySelectorAll
}
Makered.prototype.makered=function() {
this.el.style.color="red";
}
var box = new Makered('#box');
box.makered();
// === WITH DEFAULT OPTIONS === //
//http://stackoverflow.com/a/42703312/4991434
//<p class="text">Lorem</p>
var Xstyle = function(elem, options) {
this.el = document.querySelector(elem); // for multiple elements use querySelectorAll
this.options = options || {};
for (var optionName in this.defaultOptions) {
if (typeof this.options[optionName] === 'undefined') {
this.options[optionName] = this.defaultOptions[optionName];
}
}
}
Xstyle.prototype.defaultOptions = {
color: "#222",
backgroundColor: "transparent",
fontSize: "16px"
}
Xstyle.prototype.xstyle = function() {
this.el.style.backgroundColor = this.defaultOptions.backgroundColor;
if (typeof this.options.backgroundColor !== 'undefined') {
this.el.style.backgroundColor = this.options.backgroundColor;
}
if (typeof this.options.color !== 'undefined') {
this.el.style.color = this.options.color;
}
if (typeof this.options.fontSize !== 'undefined') {
this.el.style.fontSize = this.options.fontSize + "px";
}
}
/* = Call plugin = */
var myText = new Xstyle(".text", {
backgroundColor: "#ccc",
color: "#444",
fontSize: 20
});
myText.xstyle();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment