I'm working on the slider with swipe effect. I'm using the example from the Youtube tutorial by Wes Bos. The problem is when I click on the parent (mousedown event) it triggers the child event too, after the mouseup event.

I tried to add the timer which will allow clicking event on the child elements, a few seconds after the mouseup event is finished.

HTML:

<div class="items">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
  <div class="item">6</div>
  <div class="item">7</div>
</div>

CSS:

.items {
  height: 300px;
  overflow: scroll;
}

.items .item {
  width: 200px;
  height: 80px;
  background: green;
  border-bottom: 1px solid red;
}

Javascript:


let clickNotAllowed = false;

// ------------------- Tutorial ------------------- //
const slider = document.getElementsByClassName('items')[0];
let isDown = false;
let startY;
let scrollTop;
let speed = 0.5;


// Mouse down will trigger the parent event (swipe), but also the child event will
// be added to the list of events which need to be executed
slider.addEventListener('mousedown', (e) => {
  isDown = true;
  startY = e.pageY - slider.offsetTop;
  scrollTop = slider.scrollTop;
});

slider.addEventListener('mouseleave', () => {
  isDown = false;
  clickNotAllowed = false;
});

slider.addEventListener('mouseup', () => {
  isDown = false;

  // Not part of the tutorial
  // I tried to set the timer so a few ms after the mouse is up
  // I'm setting the clickNotAllowed to true so the user will be able to click
  // Before this timer is finished, click event on the child will try to execute itself
  setTimeout(function() {
    clickNotAllowed = false;
  }, 200);

});

slider.addEventListener('mousemove', (e) => {

  if(!isDown) return;
  e.preventDefault();
  const x = e.pageY - slider.offsetTop;
  const walk = (x - startY) * speed;
  slider.scrollTop = scrollTop - walk;

  // --- Not part of tutorial --- //
  clickNotAllowed = true;

});

// ============= NOT PART OF THE TUTORIAL ============= //
const item = document.getElementsByClassName("item");

for(let i = 0; i < item.length; i++) {

    item[i].addEventListener("click", function(e) {

    if(clickNotAllowed) return;

    e.target.style.background = "blue";

  });

}

The expected result is when I click on the parent (slider - items class) and mousedown event is fired, child event should not be executed after the mouseup for parent element is executed.

0 Answers