Say I had code like so:
function on(loc,type,func){
loc.addEventListener(type, function(e){
func(e);
});
}
If I called it like this:
on(document.getElementById('test'),"click",function(){
alert('You clicked!');
});
It would work, but I want to be able to call the on function like so:
document.getElementById('test').on('click', function(){
alert('You clicked!');
});
How can I make it able to be called like so?
2 Answers 2
As has been pointed out, the DocumentElement does not have an .on() method. Yet!
You can, however, add one by extending the prototype, adding a new property and making your function available on all Elements. This is quite easy (and I'll provide a trivial example in a moment), but it's also widely considered to be a bad practice. So before you try this out, understand that Javascript absolutely does make it possible...but that doesn't mean it's a good idea.
Now, that example:
Element.prototype.test = function() {
console.log("Successfully extended the prototype of a native object!");
}
document.getElementById("footer").test();
Comments
You cannot do this because the DocumentElement does not have a property (or allow you to create one (that I know of)) of your on function.
You could get away with doing something similar such as modifying your on function to handle the onlcick event for a given element. I haven't tested the below code but it should give you an idea:
function on (element) {
var obj = {
clickEvent : function () {
element.onclick = function () {
alert("you clicked");
}
}
};
return obj;
}
var theElement = document.getElementById("test");
on(theElement).clickEvent();
onis not a property of DocumentElement. You can't do that.$function, which returns its own object, not document elements.$("#foo")is not the same asdocument.getElementById('foo').HTMLElement.prototype.on = function() { ... };, but this is very frowned upon, and very bad practice. Modifying native objects could cause coding conflicts if different javascript libraries try to modify the prototype.