Touch events not working on multiple Modal boxes

BappoSlappo :

i am trying to get Touch Events to function on multiple Modal boxes so that when you tap on a button to open the Modal box on a phone, you swipe to the left/right inside the modal box and you should get an alert box telling you which way you swiped.

I have tried to use

document.getElementsByClassName("modalSwipe");

instead of

document.getElementById("modalSwipe");

which of course is the right way to target multiple elements, but then the function stops working all together and no alerts show up.

I have recreated my problem with the entire code on Codepen but here is a snippet of the js script and parts of the html that i suspect as the troublemakers.

I've been stuck on this issue for two days now and i'm beginning to question my intelligence. Is there a obvious solution that i'm not seeing here?

Thanks so much in advance!

// i suspect that a part of the problem starts within the function "init()"
var lbl;
function init() {
  lbl = document.getElementById("modalSwipe");

  lbl.addEventListener("touchstart", startTouch, false);
  lbl.addEventListener("touchend", endTouch, false);
  lbl.addEventListener("touchmove", moveTouch, false);
}

var initialX = null;
var initialY = null;

function startTouch(e) {
  initialX = e.touches[0].clientX;
  initialY = e.touches[0].clientY;
}

function endTouch() {
  initialX = null;
  initialY = null;
}

function moveTouch(e) {
  if (initialX === null) {
    return;
  }
  if (initialY === null) {
    return;
  }
  var currentX = e.touches[0].clientX;
  var currentY = e.touches[0].clientY;
  var diffX = initialX - currentX;
  var diffY = initialY - currentY;

  if (Math.abs(diffX) > Math.abs(diffY)) {
    // sliding horizontally
    if (diffX > 0) {
      alert("Left"); // swiped left
    } else {
      alert("Right"); // swiped right
    }
  } else {
    return;
  }
  e.preventDefault();
}
<section>
  <button class='button modalButton'>Modal 1</button>
  <!--and the other part of the problem lies here with modalSwipe -->
  <div class='modal modalid' id="modalSwipe">
    <div class='modal-content'>
      <!-- no content for simplicity -->
      <div class='modal-header'>
        <span class='close'>X</span>
        <h2>Modal 1</h2>
      </div>
    </div>
  </div>
</section>

Zack :

Looking at your Codepen, I noticed you use the same ID (modalSwipe) for your modals.

IDs should not be reused on multiple elements.

Instead you should try to use class names and find the active modal. You could do this by adding an extra class active to the active modal. Once you close the modal, the active class should then be removed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31989&siteId=1