1

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.

1 Answer 1

2

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);
    });
}
2
  • Thanks! So the handler is the function when I call iq.click('a', function(){? Is the handler always going to be a function? Also, according to MDN, the third parameter is useCapture, which defaults to false. Even after reading the docs I'm not entirely sure what that may be used for :-0
    – Justin
    Jun 14, 2014 at 16:06
  • Yes, the handler is always a function. Though you don't need to pass a function expression (the function(){…} thing), you can also pass variables or anything else that produces a function (handler in my answer is a variable). The useCapture flag is only interesting when it's set to true, read about the DOM event dispatch phases
    – Bergi
    Jun 14, 2014 at 16:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.