0
0

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 5 years have passed since last update.

jQueryをインストール

Last updated at Posted at 2020-12-13

インストール

% yarn add jquery

設定ファイルを書き換え

config/webpack/environment.js
const { environment } = require('@rails/webpacker')
const webpack = require('webpack')

environment.plugins.prepend('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    jquery: 'jquery',
  })
)

module.exports = environment
app/javascript/packs/application.js
// 省略

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require('jquery')
require('../articles') //記述例で使用するjsファイル

// 省略

以上で導入完了

補足

application.html.erbに以下のようにデフォルトで記述されているヘルパーメソッドのコードにより、JavaScriptの参照を行っています。

app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
  <head>
    <title>TryWebpacker</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
    <%# 上記の記述でwebpackで管理されているJavaScriptを参照している %>
  </head>

  <body>
    <%= yield %>
  </body>
</html>

記述例

jQueryを用いた記述

app/javascript/articles.js
$(function () {
  $(document).on("mouseover", "h1", function () {
    $(this).css({ "color": "blue" });
  }).on("mouseout", "h1", function () {
    $(this).css({ "color": "" });
  })
});

JavaScriptを用いた記述

app/javascript/articles.js
window.onload = function () {
  document.querySelector("h1").addEventListener("mouseover", function (event) {
    this.style.color = "blue"
  }, false);
  document.querySelector("h1").addEventListener("mouseout", function (event) {
    this.style.color = ""
  }, false);
};
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?