Reputation: 1329
I recently realized that in learning to write JavaScript using jQuery, I learned JS syntax, but I never really learned JS. So the project here is to mimic jQuery methods using only native JavaScript.
I started with a function of the global window object which returns a set of methods that I would commonly use:
window.iq = (function(){
return {
id: function(id) {
return document.getElementById(id);
},
// Several other similar methods
})();
So, now I can invoke that method like so:
iq.id('elementID') //and so forth
I'm having trouble writing a method that mimics jQuery's .click()
. I can attach a click handler to a set of elements like so:
[].forEach.call(iq.selAll('a'), function(el) { // selAll is the short version of document.querySelectorAll()
el.addEventListener('click', function(){
// do stuff
});
I haven't been able to figure out how to write a method that does that, so that each time I want to fire a click event on an element or set of elements, I can just write:
iq.click('element', function(){
// do stuff
});
Here is my non-working attempt at this:
click: function(el) {
return [].forEach.call(iq.selAll(el), function(el) {
el.addEventListener('click');
});
}
As always, I very much appreciate any advice or guidance.
Upvotes: 1
Views: 179
Reputation: 665122
Your code is missing the second parameter to the click
method, which is the actual handler function:
click: function(el, handler) {
return [].forEach.call(iq.selAll(el), function(el) {
el.addEventListener('click', handler, false);
});
}
Upvotes: 2