Search code examples
javascriptdry

How can I make a custom JS function?


Here is an idea of what I'm trying to do - a custom shorthand:

on_cl('#id' /* or .class instead of #id */){
  // insert code here
}

, to not paste this over and over:

document.querySelector('#id' /* or .class */).addEventListener('click', () => {
  // insert code here
})

. Basically, these 2 chunks of code should be equivalent.

How can I do this?

I searched for an answer on MDNdocs, but didn't find what I wanted.


Solution

  • If you want a shortcut for an already existing method, you will need to pass in the parameters of the new function everything you need to write in the original method. In your case you would need the selector and the callback of the event, so the function should look like this :

    function on_cl(selector, eventCallback){
      document.querySelector(selector).addEventListener('click', eventCallback)
    }
    

    And call it like this :

    on_cl('#id', () => {
      /// your callback
    }); 
    

    Edit

    As David Thomas suggested in the comments, it is also possible to change the event to listen to.

    In the function on_cl, the only event to listen to is "click". This can be changed by passing it as an argument of the function

    function on_event(selector, eventType, eventCallback){
      document.querySelector(selector).addEventListener(eventType, eventCallback)
    }
    
    on_event('#id', 'click', () => {
      /// your callback
    }); 
    
    

    If you want, you can then create multiple shortcuts for each event you need to listen to, like this :

    function on_click(selector, eventCallback){
      on_event(selector, "click", eventCallback);
    }
    
    function on_mouse_up(selector, eventCallback){
      on_event(selector, "mouseup", eventCallback);
    }
    
    // etc...