adding multiple event listeners to one element

后端 未结 14 1466
夕颜
夕颜 2020-11-27 13:12

So my dilemma is that I don\'t want to write the same code twice. Once for the click event and another for the touchstart event.

Here is the original co

14条回答
  •  野性不改
    2020-11-27 13:23

    This is my solution in which I deal with multiple events in my workflow.

    let h2 = document.querySelector("h2");
    
    function addMultipleEvents(eventsArray, targetElem, handler) {
            eventsArray.map(function(event) {
                targetElem.addEventListener(event, handler, false);
            }
        );
    }
    let counter = 0;
    function countP() {
        counter++;
        h2.innerHTML = counter;
    }
    
    // magic starts over here...
    addMultipleEvents(['click', 'mouseleave', 'mouseenter'], h2, countP);

    MULTI EVENTS DEMO - If you click, move away or enter the mouse on the number, it counts...

    0

提交回复
热议问题