14
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rails 5.2 jQuery 動かし方(turbolinks含む)

Last updated at Posted at 2018-10-07

jqueryを動かすのに結構時間がかかってしまったので、備忘録程度に書いてきます。3ステップで簡単にできます。

###1 gem "jquery-rails"のインストール
Gemfileに書いて、bundle installをします。
###2 //= require jqueryをapplication.jsに追加

書く場所が読み込む順番に影響を与えるので、重要です。

app/assets/javascripts/application.js

//
//= require jquery
//= require rails-ujs
//= require activestorage
//= require turbolinks
//= require_tree .

###3 viewが読み込まれてからjqueryが読み込まれるようにします。

app/assets/javascripts/application.js

$(document).ready(function() {
    $("button").text("Hello JQuery on Rails");
 });

こういう風にかくとviewの後に読み込まれます。

注意 : turbolinksが動いている場合(ページ遷移した場合など)は上のreadyイベントは呼び出されませ。そうなので、下のように書くと、初期ロード時や、ページ遷移時など常に動きます。

app/assets/javascripts/application.js
$(document).on('turbolinks:load', function() {
    $("button").text("Hello JQuery on Rails");
});
14
12
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?