Jquery アコーディオン 最低限


Laravel Framework 8.35.1
開発環境
docker,vscode
今日はjqueryでアコーディオンを作成したいと思います
アコーディオンとは下の動画を見てください。
非同期で操作でできると思います。

今回はLaravelを用いて作成します
まずresourceフォルダにtop.blade.indexを作成します

top.blade.php
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
  <link href = "css/hoge.css" rel = "stylesheet" type = "text/css">
</head>
<body>
<ul class = "faqs">
  <li class = "faq">
    <h1 class = "question">Windowsでも受講できますか</h1>
    <span>+</span>
    <div class = "answer">
      <p>Windowsでも受講は可能ですがMacをおすすめします</p>
    </div>
  </li>
  <li class = "faq">
    <h1 class = "question">年齢制限はありますか?</h1>
    <span>+</span>
    <div class = "answer">
      <p>年齢制限は特にありません</p>
    </div>
  </li>
</ul>
  <script src = "{{asset('js/hoge.js')}}"></script>
</body>

このようにcssファイルを読み込ませます
次にpublicフォルダにcssファイルを作成します

hoge.css
.faqs{
    margin:10px;
    border-bottom:1px solid #ccc;
    position:relative;
    cursor:pointer;
    text-align: left;
}
.faq{
 cursor:pointer;
}
.answer{
 display:none;
}

次にpublicフォルダにjsファイルを読み込ませます

hoge.js
$('.faq').click(function(){
  var $answer = $(this).find('.answer');
  if($answer.hasClass('open')){
    $answer.removeClass('open');
    $answer.slideUp();
    $(this).find('span').text('+');
  }else{
    $answer.addClass('open');
    $answer.slideDown('open');
    $(this).find('span').text('-');
  }


});

完成