<やりたいこと>
railsでjqueryを動かしたい!!
web上で調べた方法がうまくいかず、質問しています。
コードはこちらです。
layouts/apprication.html.erb
<!DOCTYPE html> <html> <head> <title>Seasoning</title> <%= csrf_meta_tags %> <%= csp_meta_tag %> <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> <script src="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script> <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> </head> <body> <%= yield %> </body> </html>
assets/javascripts/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's // vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. JavaScript code in this file should be added after the last require_* statement. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require rails-ujs //= require activestorage //= require turbolinks //= require_tree .
assets/javascripts/index.js
$(function() { // 「Open」ボタンをクリック時に、fadeInメソッドでHTML要素を表示する $('#open').on('click', function() { $('#overlay, #modalWindow').fadeIn(); }); // 「Close」ボタンをクリック時に、fadeOutメソッドでHTML要素を非表示にする $('#close').on('click', function() { $('#overlay, #modalWindow').fadeOut(); }); locateCenter(); // => モーダルウィンドウを中央配置するための初期値を設定する $(window).resize(locateCenter); // => ウィンドウのリサイズに合わせて、モーダルウィンドウの配置を変える // モーダルウィンドウを中央配置するための配置場所を計算する関数 function locateCenter() { let w = $(window).width(); let h = $(window).height(); let cw = $('#modalWindow').outerWidth(); let ch = $('#modalWindow').outerHeight(); $('#modalWindow').css({ 'left': ((w - cw) / 2) + 'px', 'top': ((h - ch) / 2) + 'px' }); } });
index.html.erb
<% @flavors.each do |flavor| %> <div> <%= flavor.name %> <%= flavor.price %> <%= flavor.status %> <button id="edit">編集</button> <div id="overlay"></div> <div id="modalWindow"> <p>テスト</p> <button id="close">閉じる</button> </div> </div> <% end %>
<試したこと>
・gemfileにgem 'jquery-rails'とgem 'jquery-ui-rails'と記入し、bundle installを行い、rails sを立ち上げなおした。
・appllication.jsに//= require jqueryと//= require jquery_ujsを記入した。
・applicaiton.html.erbに<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>が記載されていることを確認した。
以上です。
何卒お力添えよろしくお願いします。
こちらの情報不足などで、追加で何か聞きたいことがあれば、ぜひ聞いてください。
よろしくお願いします。
エディター上に$ is not defined, please fix or add /global $/とエラーが出ています。調べたところ、jqueryをcdnで読み込む前にjqueryの関数を使おうとしているからだそうで、一番最初に変えいてある、window.addEventListener(~~~を追加しました。https://pisuke-code.com/jquery-is-not-defined-solution/
回答1件
あなたの回答
tips
プレビュー