【jQuery】アハ体験

⚠この記事が公開されたのは 2021年11月17日で、内容が古く、間違っている可能性があります。

アハ体験のデモコンテンツをjqueryで作成してみました。

See the Pen Untitled by 本田類二 (@curledtail_h) on CodePen.

<div class="container mx-auto py-3">
  <!-- アハ体験コンテンツ -->
  <div class="aha d-block mx-auto">
    <div class="wrapper_img">
      <img class="img-fluid" src="https://placehold.jp/300x300.png?text=アハ画像①" alt="アハ画像①">
      <img class="img-fluid" src="https://placehold.jp/300x300.png?text=アハ画像②" alt="アハ画像②">
    </div>
  </div>
  <!-- プログレスバー -->
  <div id="progress" class="progress mt-3">
    <div class="progress-bar notransition" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0"></div>
  </div>
  <!-- アハ体験ボタン -->
  <div class="text-center py-3"><button id="start-aha" class="btn btn-primary">スタート</button></div>
</div>
/*---- アハ体験 ----*/
.aha {
  position: relative;
  max-width: 300px; /* アハ画像のナチュラルサイズ */
  height: 300px;
}

.aha .wrapper_img img {
  position: absolute;  
  top: 0;
  left: 0;
}

.aha .wrapper_img img:last-child { /* 2枚目のアハ画像 */
  display: none;
  z-index: 100;
}
/* Bootstrapのプログレスバーのアニメーションを無効化
[NOTE]繰り返しアニメーションさせた場合の初期化動作まで実装していない為 */
.notransition {
  -webkit-transition: none !important;
  transition: none !important;
}
const progressBar = function(id){
  const frame = $(id);
  const bar = $('div.progress-bar', frame);
  let current = 0;
  return {
  current: function(){
    $('#start-aha').prop('disabled', true); //実行中はスタートボタンを無効にする
    return current;
  },
  set: function(n) {
    current = (n > 100) ? 100 : n;
    bar
    .css('width', current + '%')
    .prop('aria-valuenow', current)
    return this;
  },
  show: function() {
    this.set(0);
    frame.addClass('show');
    return this;
  },
  complete: function(){
    $('#start-aha').prop('disabled', false);  //終了したらはスタートボタンを有効にする
    return this;
  },
  };
};
$('#start-aha').on('click', function() { //スタートボタンが押されたら
  $('.wrapper_img img:last-child').attr('src', 'https://placehold.jp/300x300.png?text=アハ画像②');
  $('.wrapper_img img:last-child').hide(); //2枚目の画像を非表示にする
  setTimeout(function(){
    setTimeout(function(){ //2枚目の画像を2秒間待ったあと7秒間かけてフェードイン
      $('.wrapper_img img:last-child').fadeIn(7000);
    }, 2000);
    const progress = new progressBar('#progress');
    const timer = setInterval(function() {
      const current = progress.current();
      if (current < 100) { //プログレスバーが100%未満なら
      // プログレスバーの更新処理
      const n = 1;
      progress.set(current + n);
      } else {
      // プログラスバーが100%以上なら
      progress.complete();
      $('.wrapper_img img:last-child').attr('src', 'https://placehold.jp/18/cccccc/999999/300x300.png?text=もう一度チャレンジする場合はスタートボタンを押してね'); //2枚目の画像を非表示にする
      clearInterval(timer);
      $(".progress-bar").addClass("notransition");
      }
    }, 100)
  });
});

参考

https://www.weblab.co.jp/staff/creator/1057.html