0

I think there's an easy answer, but I can't find the right solution for this. I know that it has to be done with querySelectorAll, but can't figure out how to use it in this case.

I have elements with ID's #modalA, #modalB and #modalC. I don't want to duplicate code. So I want to figure out what is the best practice for this?

Can't use getElementByClassName, because I can't make changes to markup.

var getModalsA = document.getElementById('modalA');
var getModalsB = document.getElementById('modalB');
var getModalsC = document.getElementById('modalC');

getModalsA.addEventListener('touchmove', function(e) {

    e.preventDefault();

}, false);
Elvis
  • 39
  • 8

1 Answers1

0

I'm not sure if you're simply after a small refactoring.

Something like:

function addListenersToElement(id) {
  var el = document.getElementById(id);
  el.addEventListener('touchmove', function(e) {

      e.preventDefault();

  }, false);
}

var ids = ['modalA', 'modalB', 'modalC'];
ids.forEach(addListenersToElement);

I would use jQuery or similar for stuff like this (or a lightweight variant), but if you can't change the page markup, probably your best bet is to refactor the code in smaller functions.

Alberto Chiesa
  • 7,022
  • 2
  • 26
  • 53