adding multiple event listeners to one element

后端 未结 14 1401
夕颜
夕颜 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:37
    //catch volume update
    var volEvents = "change,input";
    var volEventsArr = volEvents.split(",");
    for(var i = 0;i<volknob.length;i++) {
        for(var k=0;k<volEventsArr.length;k++) {
        volknob[i].addEventListener(volEventsArr[k], function() {
            var cfa = document.getElementsByClassName('watch_televised');
            for (var j = 0; j<cfa.length; j++) {
                cfa[j].volume = this.value / 100;
            }
        });
    }
    }
    
    0 讨论(0)
  • 2020-11-27 13:40

    What about something like this:

    ['focusout','keydown'].forEach( function(evt) {
            self.slave.addEventListener(evt, function(event) {
                // Here `this` is for the slave, i.e. `self.slave`
                if ((event.type === 'keydown' && event.which === 27) || event.type === 'focusout') {
                    this.style.display = 'none';
                    this.parentNode.querySelector('.master').style.display = '';
                    this.parentNode.querySelector('.master').value = this.value;
                    console.log('out');
                }
            }, false);
    });
    
    // The above is replacement of:
     /*   self.slave.addEventListener("focusout", function(event) { })
          self.slave.addEventListener("keydown", function(event) {
             if (event.which === 27) {  // Esc
                }
          })
    */
    
    0 讨论(0)
  • 2020-11-27 13:41

    I know this is an old question, but I thought some might find this approach useful; it could be applied to any similarly repetitive code:

    ES6

    ['click','ontouchstart'].forEach( evt => 
        element.addEventListener(evt, dosomething, false)
    );
    

    ES5

    ['click','ontouchstart'].forEach( function(evt) {
        element.addEventListener(evt, dosomething, false);
    });
    
    0 讨论(0)
  • 2020-11-27 13:41

    You can just define a function and pass it. Anonymous functions are not special in any way, all functions can be passed around as values.

    var elem = document.getElementById('first');
    
    elem.addEventListener('touchstart', handler, false);
    elem.addEventListener('click', handler, false);
    
    function handler(event) {
        do_something();
    }
    
    0 讨论(0)
  • 2020-11-27 13:41

    Simplest solution for me was passing the code into a separate function and then calling that function in an event listener, works like a charm.

    function somefunction() { ..code goes here ..}
    
    variable.addEventListener('keyup', function() {
       somefunction(); // calling function on keyup event
    })
    
    variable.addEventListener('keydown', function() {
       somefunction(); //calling function on keydown event
    })
    
    0 讨论(0)
  • 2020-11-27 13:41

    Semi-related, but this is for initializing one unique event listener specific per element.

    You can use the slider to show the values in realtime, or check the console. On the <input> element I have a attr tag called data-whatever, so you can customize that data if you want to.

    sliders = document.querySelectorAll("input");
    sliders.forEach(item=> {
      item.addEventListener('input', (e) => {
        console.log(`${item.getAttribute("data-whatever")} is this value: ${e.target.value}`);
        item.nextElementSibling.textContent = e.target.value;
      });
    })
    .wrapper {
      display: flex;
    }
    span {
      padding-right: 30px;
      margin-left: 5px;
    }
    * {
      font-size: 12px
    }
    <div class="wrapper">
      <input type="range" min="1" data-whatever="size" max="800" value="50" id="sliderSize">
      <em>50</em>
      <span>Size</span>
      <br>
      <input type="range" min="1" data-whatever="OriginY" max="800" value="50" id="sliderOriginY">
      <em>50</em>
      <span>OriginY</span>
      <br>
      <input type="range" min="1" data-whatever="OriginX" max="800" value="50" id="sliderOriginX">
      <em>50</em>
      <span>OriginX</span>
    </div>

    0 讨论(0)
提交回复
热议问题