Home > database >  JS - How can I prevent that if the translate isn't finished yet, I can't press the button?
JS - How can I prevent that if the translate isn't finished yet, I can't press the button?

Time:12-08

When I click the Slider Button, the transform of the Slider changes. This animation lasts 1 second. How can I prevent, that if the translate isn't finished yet, I can't press the button?

// Slider Button Navigation
sliderBtnLeft.addEventListener("click", () => {

    // Container Width
    x = slider.clientWidth;

    // Get the Slider TranslateX value
    tempTranslateX = getTranslateX(slider);

    // Check for first Slider Element
    if(tempTranslateX >= 0)
    {
        // Set translate, to show last item
        slider.style.transform = "translateX(-"   (amountElems - 1) * x   "px)";   
    }
    else
    {
        // Set tranlate, to show next (left) item
        tempTranslateX  = x;
        slider.style.transform = "translateX("   tempTranslateX   "px)";
    }
});

// Function to get Translate Value
function getTranslateX(elem) {
    let style = window.getComputedStyle(elem);
    let matrix = new WebKitCSSMatrix(style.transform);
    return matrix.m41;
}

CodePudding user response:

One way to prevent the user from clicking the button again before the animation finishes is to use a flag variable to track the animation state. You can set this flag to true when the animation starts and set it back to false when the animation finishes. You can then check the value of the flag before allowing the user to click the button again.

let isAnimating = false; // Flag to track animation state

// Slider Button Navigation
sliderBtnLeft.addEventListener("click", () => {
  // Check if the animation is still in progress
  if (isAnimating) {
    return;
  }

  // Set the flag to true to indicate that the animation is in progress
  isAnimating = true;

  // Container Width
  x = slider.clientWidth;

  // Get the Slider TranslateX value
  tempTranslateX = getTranslateX(slider);

  // Check for first Slider Element
  if(tempTranslateX >= 0) {
    // Set translate, to show last item
    slider.style.transform = "translateX(-"   (amountElems - 1) * x   "px)";
  } else {
    // Set tranlate, to show next (left) item
    tempTranslateX  = x;
    slider.style.transform = "translateX("   tempTranslateX   "px)";
  }

  // Wait for the animation to finish
  setTimeout(() => {
    // Set the flag to false to indicate that the animation has finished
    isAnimating = false;
  }, 1000); // The animation lasts 1 second
});

// Function to get Translate Value
function getTranslateX(elem) {
  let style = window.getComputedStyle(elem);
  let matrix = new WebKitCSSMatrix(style.transform);
  return matrix.m41;
}

CodePudding user response:

You can disable the button by default and You can make use of transitionend event to enable it once the transition is completed. requestAnimationFrame would work too.

  • Related