Phillip Senn Phillip Senn - 8 months ago 68
Javascript Question

Assigning the same event listener to multiple buttons

I've found that touchstart works better than the click event when working with my iPad, so I would like to use touchstart instead of 'click'.

Q: How do I refactor the JavaScript portion of the following? I used to have a single

$(document).on('click','.number',pgm.number)




pgm = {}
pgm.number = function() {
console.log(this) // etc
}
btn1.addEventListener('touchstart', pgm.number, false)
btn2.addEventListener('touchstart', pgm.number, false)
btn3.addEventListener('touchstart', pgm.number, false)
btn4.addEventListener('touchstart', pgm.number, false)
btn5.addEventListener('touchstart', pgm.number, false)
btn6.addEventListener('touchstart', pgm.number, false)
btn7.addEventListener('touchstart', pgm.number, false)
btn8.addEventListener('touchstart', pgm.number, false)
btn9.addEventListener('touchstart', pgm.number, false)
btn0.addEventListener('touchstart', pgm.number, false)

<button id="btn1" class="number">1</button>
<button id="btn2" class="number">2</button>
<button id="btn3" class="number">3</button>
<button id="btn4" class="number">4</button>
<button id="btn5" class="number">5</button>
<button id="btn6" class="number">6</button>
<button id="btn7" class="number">7</button>
<button id="btn8" class="number">8</button>
<button id="btn9" class="number">9</button>
<button id="btn0" class="number">0</button>




Answer Source

Add the touchstart to the document and use the event target to check if the element has the className ".number". This is the closest to jQuery's event delegation:

pgm.number = function(e) {
    var t = e.target;                               // get the taget of the event (the element that got touchstarted)
    if(t.classList.contains("number")) {            // if it has a class of .number
        console.log(t);                             // log it (use it)
    }
}

document.addEventListener("touchstart", pgm.number, false);

Example using click:

var pgm = {};
pgm.number = function(e) {
  var t = e.target;
  if (t.classList.contains("number")) {
    console.log(t);
  }
}

document.addEventListener("click", pgm.number, false);
<button id="btn1" class="number">1</button>
<button id="btn2" class="number">2</button>
<button id="btn3" class="number">3</button>
<button id="btn4" class="number">4</button>
<button id="btn5" class="number">5</button>
<button id="btn6" class="number">6</button>
<button id="btn7" class="number">7</button>
<button id="btn8" class="number">8</button>
<button id="btn9" class="number">9</button>
<button id="btn0" class="number">0</button>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download