After delving into learning JavaScript through jQuery, I realized that while I had mastered the syntax of JS, I hadn't truly grasped the core concepts. This sparked a project where I aimed to replicate jQuery methods using pure JavaScript.
I kicked things off by creating a function within the global window object that includes a set of commonly used methods:
window.iq = (function(){
return {
id: function(id) {
return document.getElementById(id);
},
// Other similar methods go here
})();
Now, I can call this method as follows:
iq.id('elementID') //and so on
However, I'm facing a challenge with replicating jQuery's .click()
method. While I've managed to add a click handler to elements with the following code:
[].forEach.call(iq.selAll('a'), function(el) { // selAll is shorthand for document.querySelectorAll()
el.addEventListener('click', function(){
// carry out actions
});
I haven't been successful in creating a method that allows me to fire a click event on an element or group of elements simply by writing:
iq.click('element', function(){
// carry out actions
});
Below is my unsuccessful attempt at achieving this:
click: function(el) {
return [].forEach.call(iq.selAll(el), function(el) {
el.addEventListener('click');
});
}
Any advice or guidance on this matter would be greatly appreciated.