jQueryの準備
jQueryを使用するには、jQueryライブラリを読み込む必要がある。
jQueryの読込
index.html<head> <script src="https://...jQuery.min.js"></script> </head>
jQueryファイルの読込
index.html<head> ・・・ </head> <body> ・・・ <script src="script.js"></script> </body>
bodyの終了タグの直前で読み込む。
jQueryの型
基本的な型
script.js$(document).ready(function() { // この中にjQueryを書く });
readyイベントの省略
script.js$(function() { // この中にjQueryを書く });
モーダルを表示
①モーダルをcssで非表示にする。
stylesheet.css.login-modal-wrapper { display: none; }
②ログインボタンにクリックイベントを設定
③clickイベントでモーダルを表示
$('#login-show').click(function() { $('#login-modal').fadeIn(); });
モーダルを隠す
閉じるボタンをクリックした時に、モーダルが閉じるようにする。
$('.close-modal').click(function() { $('#login-modal').fadeOut(); });
addClass・removeClass
addCrassメソッドを用いるとクラスを追加することができ、removeClassメソッドは反対にクラスを取り除くことができる。
addClass
$('.text-contents').addCrass('text-active'); // クラス名の前にドットは不要
removeClass
$('.text-contents').removeCrass('text-active'); // クラス名の前にドットは不要
this find 復習
thisに.マウスが乗っているlesson-hoverクラスが入ってfindでその中の.text-contentsを取得している。
$('.lesson-hover').hover( function() { $(this).find('.text-contents').addClass('text-active'); }, function() { $(this).find('.text-contents').removeClass('text-active'); } );
hasClassメソッド
hasClassメソッドは、引数に指定したクラスを、オブジェクトが持っているか判定する時に使用する。
オブジェクトがそのクラスを持っていればtrue、持っていなければfalseを返す。
index.html<div class="answer">・・・</div> <div class="answer open">・・・</div>
script.js$('.answer').hasClass('open'); // 結果: false $('.answer open').hasClass('open'); // 結果: true
hasClassを用いたアコーディオン
script.jsif ($('.answer').hasClass('open')) { // openクラスを外す処理 // 答えを隠す処理 } else { // openクラスをつける処理 // 答えを表示する処理
script.js$('.faq-list').click(function() { var $answer = $(this).find('.answer'); if ($('.answer').hasClass('open')) { // answerにopenがある場合 $answer.slideUp(); $answer.removeClass('open') } else { // そうでない場合 $answer.slideDown(); $answer.addClass('open'); } });