swiperの導入
前回作ったアプリを元に、swiper
を導入してみようと思います。
swiperとは
スライダーが作れるJavaScriptのライブラリです。
こんなやつです。よく見ますよね。
導入
いくつか方法があるようですが僕はyarn
を使いました。
yarn自体のインストール方法は省略します。
yarn add swiper
を実行するとpackage.json
というファイルに
"dependencies": { "swiper": "^6.8.1" },
このような記載が増えていると思います。
yarn install
でインストールするとnode_modules
というディレクトリにswiperに関するファイルが追加されます。
ファイルの読み込み
必要なファイルをapplication.js
、application.css.scss
で読み込みます。
// application.js //= require jquery //= require swiper/swiper-bundle.js
swiperはjquery不要、という記事を見たんですがやり方がわからず、jqueryを入れたら動きました。
なのでGemfileにgem 'jquery-rails'
を追加してbundle install
します。(変なタイミングですんません)
/* application.css.scss */ @import 'swiper/swiper-bundle';
あとはpathを通すための設定をしておきます。
# config/initializers/assets.rb Rails.application.config.assets.paths << Rails.root.join('node_modules')
コードを記述
準備ができたので実際にコードを書いていきます。
公式にも見本のコードがありますが、こちらのサイトが分かりやすかったので参考にさせていただいてます。
slim形式にしてviewファイルの表示したい箇所に記述します。
また、今回はJavaScriptのコード量が少ないのでここに一緒に書いてしまいます。
# show.html.slim .swiper-container .swiper-wrapper .swiper-slide | Slide 1 .swiper-slide | Slide 2 .swiper-slide | Slide 3 .swiper-slide | Slide 4 javascript: $(document).ready(function() { new Swiper('.swiper-container', { loop: true, autoplay: { delay: 1000, }, }) })
loop、autoplay以外にも色々できるので公式のDemosのページを見ていただけると良いかと思います。
/* application.css.scss */ .swiper-container { width: 600px; height: 300px; } /* 全体のスタイル */ .swiper-wrapper { width: 100%; height: 250px; } /* 全スライド共通スタイル */ .swiper-slide { color: #ffffff; width: 100%; height: 100%; text-align: center; line-height: 250px; } /* 4の倍数+1枚目のスライドのスタイル(1枚目、5枚目…) */ .swiper-slide:nth-child(4n+1) { background-color: #EECB27; } /* 4の倍数+2枚目のスライドのスタイル(2枚目、6枚目…) */ .swiper-slide:nth-child(4n+2) { background-color: #E13239; } /* 4の倍数+3枚目のスライドのスタイル(3枚目、7枚目…) */ .swiper-slide:nth-child(4n+3) { background-color: #1F1762; } /* 4の倍数+4枚目のスライドのスタイル(4枚目、8枚目…) */ .swiper-slide:nth-child(4n+4) { background-color: #BEDAE5; }
ではどのようになっているか、ブラウザで確認してみます。
ちゃんと動いてます。
せっかく前回、画像を複数登録できるアプリを作ったので、その画像を表示させてみます。
# show.html.slim .swiper-container .swiper-wrapper - if @user.images.attached? - @user.images.each do |image| = image_tag image, class: 'swiper-slide'
これで確認してみます。
ちゃんと登録された画像が順番に表示されました。
最後に
そんなに難しいことではないんでしょうが、ライブラリやプラグインを入れるとなると少し身構えてしまいます。
便利なのは確かなので慣れていきたいです。
では今回は以上です。ありがとうございました。
参考サイト
Swiper - The Most Modern Mobile Touch Slider
サンプル付き!簡単にスライドを作れるライブラリSwiper.js超解説(基礎編) | ガリガリコード
swiperをyarnで導入して、画像をスライダー形式にする! - Qiita
jQueryで $ is not define エラーが出たときの一番簡単な解決法 | PisukeCode - Web開発まとめ