How to return "addEventListener()" from another function - Javascript

1166 views javascript
1

I am trying to make my code shorter and more optimized, and want to make it look clearer.

So far I did this :

function id(a) {
  return document.getElementById(a);
}

function cl(a) {
  return document.getElementsByClassName(a);
}

function tg(a) {
  return document.getElementsByTagName(a);
}

function qs(a) {
  return document.querySelector(a);
}

function qa(a) {
  return document.querySelectorAll(a);
}

Now I have the possibility to call qs("#myElement"). Now I want to attach a event to the specified element just like qs("#myElement").addEventListener("click", callBack). It works great for me. But when I try to make this :

function ev(e, call) {
  return addEventListener(e, callback);
}

And then try to call qs("#init-scrap").ev("click", someFunction) then it pops up the following error :

Uncaught (in promise) TypeError: qs(...).ev is not a function.. I don't know what is the problem, do I have to try method chaining ? or any other way I can resolve this problem.

Note : I don't want to use any libraries or frameworks liek Jquery etc.

answered question

2 Answers

4

Just pass the element/nodelist in as the first argument and attached the listener to it.

function ev(el, e, call) {
  return el.addEventListener(e, callback);
}

posted this
0

There is an error in your ev method. It should be

const ev = document.addEventListener;

So instead of creating new functions that should behave the same, you are aliasing the actual function.

posted this

Have an answer?

JD

Please login first before posting an answer.