0

I have below code

[...document.getElementsByClassName("numericOnly")].forEach(node => {
                console.log(node)
                node.addEventListener('keypress', function (event) {
                    console.log(event)
                }, false);
                node.addEventListener('keyup', function (event) {
                    console.log(event)
                }, false);
            });

But i want to try some thing like below which is not working

[...document.getElementsByClassName("numericOnly")].forEach(node => {
                console.log(node)
                node.addEventListener('keypress,keyup', function (event) {
                    console.log(event)
                }, false);
          });

Also trying like below but that is nested

 ["keypress", "keyup"].forEach(function (event) {
                    [...document.querySelectorAll('.numericOnly')].forEach(node => {
                        console.log(node)
                        node.addEventListener('keypress', function (event) {
                            console.log(event)
                        }, false);
                    })
                });

Anyway to get this without nested some thing

[...document.getElementsByClassName("numericOnly")].forEach(node => {
                console.log(node)
                node.addEventListener('keypress,keyup', function (event) {
                    console.log(event)
                }, false);
          });

Thanks

Md. Parvez Alam
  • 4,326
  • 5
  • 48
  • 108
  • 2
    What is wrong with your first example? – Nick Parsons Sep 23 '19 at 10:49
  • To be honest, I'm not sure what you are looking for? You can create a wrapper like **[this](https://jsfiddle.net/RajeshDixit/2nwpxefc/1/)** or put the entire code in a generic function that accepts selector and attaches events like **[this](https://jsfiddle.net/RajeshDixit/2nwpxefc/4/)** – Rajesh Sep 23 '19 at 11:01
  • Your 3rd snippet would have worked if you used `event` in place of hard-coded "keypress". (Not withstanding you'd used the variable `event` twice) – Jamiec Sep 23 '19 at 11:01

2 Answers2

0

As per docs, you cannot have more than one event name attached in one call.

You can however create a utility function that can generically work for any combination for a given eveny list

Idea

  • Create a function that accepts following:
    • Selector: This will allow you to fetch elements based on any attribute.
    • EventList: This is a comma separated list of events you need to attach.
    • Handler: This is the actual common handler for events passed
    • Option: To decide when to execute the said event (bubbling/capture phase).

Following is a sample of such function with possible call

function registerEventHandler(selector, events, handler, option) {
  [...document.querySelectorAll(selector)].forEach(node => {
    events.split(',').forEach(function(eventName) {
      node.addEventListener(eventName, handler, option);
    })
  });
}

const handler = function(event) {
  console.log(event)
};

registerEventHandler('.numericOnly', 'keypress,keyup', handler, false);
registerEventHandler('.numericAndAlphabet', 'keypress,change', handler, false)
Community
  • 1
  • 1
Rajesh
  • 24,354
  • 5
  • 48
  • 79
  • **Note:** If you think there is anything incorrect/ not required in this answer, please do share your suggestion along with your vote – Rajesh Sep 23 '19 at 11:14
  • Could you please let me know y below link is not work – Md. Parvez Alam Sep 23 '19 at 11:49
  • @Md.ParvezAlam could you please inform me what you are expecting? – Rajesh Sep 23 '19 at 14:00
  • That is fine now. – Md. Parvez Alam Sep 26 '19 at 05:36
  • One request could you please let me know work of spread operator here [...document.getElementsByClassName("numericOnly")], becuase without this it was not working – Md. Parvez Alam Sep 26 '19 at 05:37
  • Its just converting NodeList to Array. You can alternatively try `Array.from` or `Array.prototype.slice.call(List)`. For more info, refer: https://stackoverflow.com/questions/3199588/fastest-way-to-convert-javascript-nodelist-to-array – Rajesh Sep 26 '19 at 06:17
-1

If your question is how to bind an eventhandler to multiple events the answer is: either you don't or you do it in the way you call 'nested':

document.querySelectorAll('.numeric-only').forEach((node) => {
  ['keypress', 'keyup'].forEach((event) => {
    console.log(`binding ${event} to`, node)
    node.addEventListener(event, () => {
      console.log(event)
    }, false);
  })
});
<input class="numeric-only">
Joschi
  • 2,874
  • 1
  • 18
  • 23