简体   繁体   中英

JS/jQuery - first click ignores first animation, every other click works properly

I built this slider, but when I run it on a page, the first click doesn't trigger the first animation. It triggers the second animation and every other click after that triggers both animations properly. What am I missing with the first click?

// SLIDER

$(".dot").click(function(){

  let currentId = ($(".dot-active").attr("id")[$(".dot-active").attr("id").length - 1]);
  let nextId = event.target.id[(event.target.id).length - 1];

  $(".dot-active").removeClass("dot-active");
  $("#" + event.target.id).addClass("dot-active");

  if(Number(currentId) != Number(nextId)){
    if(Number(currentId) < Number(nextId)){
      $("#slide" + currentId).hide("slide", { direction: "left" }, 350);
    } else {
      $("#slide" + currentId).hide("slide", { direction: "right" }, 350);
    };
    $("#slide" + currentId).removeClass("slide-active");
    $("#slide" + currentId).addClass("slide-inactive");


    if(Number(currentId) < Number(nextId)){
      $("#slide" + nextId).show("slide", { direction: "right" }, 350);
    } else {
      $("#slide" + nextId).show("slide", { direction: "left" }, 350);
    };
    $("#slide" + nextId).removeClass("slide-inactive");
    $("#slide" + nextId).addClass("slide-active");
  };
});

made a test version in codepen here: https://codepen.io/Jankko/pen/ZEEEJxL

You have to add style="display:block" to the initiation of your active slide, to prevent the instant hiding of the element, just like this:

<div id="slide2" class="slide slide-active" style="display: block;">
        ...
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM