How To load js only in one page of my app - ruby-on-rails

I'm trying to load a js file into a single page of my app. But it is called in all and this ends up generating errors on my screen.
My application.js is:
//= require jquery
//= require rails-ujs
//= require activestorage
//= require turbolinks
//= require_tree .
My application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Netshow</title>
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
<body>
<div class='cover-container d-flex w-100 h-100 p-3 mx-auto flex-column'>
<header class='masthead mb-auto'>
<%= render 'shared/navbar' %>
</header>
<%= yield %>
<footer class='mastfoot mt-auto'>
<%= render 'shared/footer' %>
</footer>
</div>
</body>
</html>
My js file is:
$(document).on("turbolinks:load", function() {
console.log('teste')
var player = videojs('my_video_1');
var options = {};
player.on('play', function() {
$.ajax({
type: 'POST',
url:"/video_clicks/",
dataType: 'json',
data: {
video_click: { video_id: window.location.pathname.split('/')[2] }
},
success: function(){
$('span.video-count')[0].innerText = parseInt($('span.video-count')[0].innerText) + 1
}
});
});
function showCount(){
var id = window.location.pathname.split('/')[2]
$.ajax({
type: 'GET',
url:"/video_clicks/"+id,
dataType: 'json',
success: function(data){
console.log($('span.video-count')[0])
$('span.video-count')[0].innerText = data
}
});
}
showCount()
});
I would like to load the js file only on one page of my app and not at all. How can I do this? I have already tried removing the require_tree add content in application.html.erb and set the content in my html file, but the rails speaks that I have to add the file in assets.erb for precompilation and when I do this the other pages reload my js file.

You have multiple options in that scenario:
You can check the params[:controller] and params[:action] in application.html.erb, if that matches the specific page controller+action then only load the JS. (Better Solution)
Like:
<% if params[:controller] == 'your_controller_name' && params[:action] == 'your_action_name' %>
<%= render partial: 'shared/custom_js' %>
<% end %>
Based on this code above, I'll create a new file named custom_js.html.erb in my views > shared folder. Then write the script in that file inside <script></script> tag. Also, you need to remove that script file from application.js file.
You can create a different layout for that specific page access method. Like the answer here.

You just simply include that page (erb file) with <%= javascript_include_tag 'js_file_name' %>

Add to you view and
<%= javascript_include_tag 'js_file_name' %>
config/initializers/assets.rb
Rails.application.config.assets.precompile += %w(js_file_name.js)

Related

Loading position of javascript in rails app

There are two pieces of my application that seem to require that I load my javascript at different points.
Omniauth works when I place <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' within <head></head>.
Shubox (js library used to upload photos) works when I place <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' just before </body>.
Each of the two does not work when the javascript is loaded where the other requires. So, if I place the javascript line at the end of the body, omniauth does not work.
I can provide additional information if needed. Thank you in advance.
application.js
require("#rails/ujs").start()
require("turbolinks").start()
require("#rails/activestorage").start()
require("channels")
application.html.erb
<html>
<head>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
</head>
<body data-shubox="<%= Rails.application.credentials.dig(:aws, :secret_access_key) %>">
<% if flash.any? %>
<% flash.each do |key, value| -%>
<section class="flash flash__<%= key %>"><%= value.html_safe %></section>
<% end -%>
<% end %>
<%= yield %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
</body>
</html>
Because of Turbolinks your application.js needs to be in the head tag, otherwise it is evaluated twice . This can cause a problem with libraries that expect your DOM to be loaded when you initialize them - which I think is your problem with shubox.
So you should put something like this in your application.js (if you are using Turbolinks 5, for earlier version the event is called page:load)
$(document).on('turbolinks:load',() => {
new Shubox('#avatar', { key: "abcde-qwerty-12345" })
}
);
You can always create 2 packs if you need them in different places:
javascript/packs/the_one_with_turbolink.js
javascript/packs/the_one_with_shubox.js
then you can do
javascript_pack_tag :the_one_with_turbolinks
and
javascript_pack_tag :the_one_with_shubox

Js file not being loaded on Rails application

Im doing a project from scratch and getting an anoying error that Im dealing without sucess.
Im trying to add a JS file to a page not having sucess.
Those are my files:
#application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Workspace</title>
<%= stylesheet_link_tag 'application', media: 'all' %>
<%= javascript_include_tag 'application' %>
<%= csrf_meta_tags %>
</head>
<body>
<%= yield %>
</body>
</html>
And my application.js
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require welcome
//= require_tree .
My welcome.js inside /assets/javascripts:
#/assets/javascripts/welcome.js
$(document).ready(function(){
$('#present').mouseenter(function(){
alert("MouseEnter!"); // This will create an alert box
console.log("MouseEnter!"); // This will log to the JS console on your browser which is a bit nicer to read than alerts, you do not need both, just preference
$(this).fadeIn('fast',1);
});
$('#present').mouseleave(function(){
alert("MouseLeave!"); // This will create an alert box
console.log("MouseLeave!");
$(this).fadeIn('fast',0.5);
});
});
When I run the root page the JS is being shown looking at the inspector. But looks empty (i dont know if this is something usual)
src="/assets/welcome.self-877aef30ae1b040ab8a3aba4e3e309a11d7f2612f44dde450b5c157aa5f95c05.js?body=1"
If I open it using the browser it shows:
(function() {
}).call(this);
Well. Someone know what can I do to make my Javascript works?
Thanks
change your code in your application.html.erb
from:
<%= stylesheet_link_tag 'application', media: 'all' %>
<%= javascript_include_tag 'application' %>
to this:
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>

Select2 multiselect search in rails

OK, I'm trying to wrap my head around using Select2, AJAX and Rails to do a multiselect search. I haven't gotten to the search part yet as I'm trying to get the multiselect part to work first.
My Controller:
class GamesController < ApplicationController
respond_to? :html, :JSON
def index
#games = Game.order('name').all
#respond_to #games
end
end
My application.js
//= require rails-ujs
//= require turbolinks
//= require select2
//= require_tree .
$('#mySelect2').select2({
placeholder: "Choose a game",
multiple: true;
ajax: {
url: <%= games_path(format: 'json') %>,
processResults: function (data) {
return {
results: data.items
};
}
}
});
My games/index.html.erb file
Still learning
<select class="#mySelect2"></select>
My application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Sonar</title>
<%= csrf_meta_tags %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
<body>
<%= javascript_include_tag "application" %>
<%= yield %>
</body>
</html>
Routes.rb
Rails.application.routes.draw do
resources :games, only: [:index]
root to: 'games#index'
end
This presents the drop down box, but isn't populating it with the data from the database or presenting a search box to start typing for autocomplete searching.
If I'm understanding it properly, I should have the JS code in the applciation.js file, which is called from the select statement in the index.html file. The index action in the controller is pulling the data from the database in response to the json request and should then pass the info to the js function.
I do note that I don't have the JS to wait for the page to load before running though, but I tried putting that in the application.js file and it didn't change anything.
*edit - the game table has the ID column, name column and a category ID column.

Ruby on rails bootstrap css js working but not found

I have a rails application which I added the bootstrap gem
first I added this two gems
gem 'bootstrap'
gem 'sprockets-rails', :require => 'sprockets/railtie'
which installed this packages
Using bootstrap 4.0.0.alpha3
Using sprockets 3.6.0
After I modified application.scss to
// Custom bootstrap variables must be set or import before bootstrap itself.
#import "bootstrap";
Then I left application.js like this
// 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, vendor/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.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require tether
//= require bootstrap-sprockets
//= require_tree .
//= require_self
Lastly my application.html.erb is this
<!DOCTYPE html>
<html>
<head>
<title>Squirm</title>
<%= stylesheet_link_tag "bootstrap" %>
<%= javascript_include_tag "bootstrap" %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<%= render 'partials/navbar' %>
<div class="container">
<%= yield %>
</div>
</body>
</html>
Bootstrap seems to we working, but in the Google Chrome console seems not to be found
You're loading Bootstrap before you've loaded jQuery. Many of Bootstrap's components require javascript (carousel, tabs, etc.), however, most of Bootstrap will work without, which is why the Bootstrap CSS is showing on your page.
Loading Bootstrap after jQuery will fix the issue:
<!DOCTYPE html>
<html>
<head>
<title>Squirm</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= stylesheet_link_tag "bootstrap" %>
<%= javascript_include_tag "bootstrap" %>
<%= csrf_meta_tags %>
</head>
<body>
<%= render 'partials/navbar' %>
<div class="container">
<%= yield %>
</div>
</body>
</html>
Also, not 100% sure based on your code, but you may be loading bootstrap twice. It seems this line: //= require bootstrap-sprockets is already loading Bootstrap.
you need to add jquery as well normally jquery come bundled in rails app, but maybe due to some reasons its not thr in your app
add
jquery from
https://cdnjs.com/libraries/jquery/
and let us knwo if this change works.

How can I make JQuery as include file?

Now, I have this JQuery in my application.html.erb
But I see this in every html of my web site. So I want to put this in refresh_post.js, which is created in /assets/javascripts
But as you know, application.html.erb calls all JavaScript file in the directory. Because I use many and putting this
<%= javascript_include_tag "application" %>
How can I call this JQuery only when user is logged in. and Where should I make refresh_post.js at so that it won't be loaded unless user is logged in?
The purpose of doing this is for SEO. I don't want to put JavaScript in HTML.
views/application.html.erb
<% if current_user %>
<%= javascript_tag do %>
jQuery(document).ready(function () {
refreshPartialPost();
setInterval(refreshPartialPost, 1000)
});
function refreshPartialPost() {
$.ajax({
url: "/posts/refresh_partial",
type: "GET",
dataType: "script",
});
}
<% end %>
<% end %>
How about this for your application layout:
<%= javascript_include_tag 'application' %>
<% if current_user %>
<%= javascript_include_tag 'refresh_post' %>
<% end %>
Have a look at this, Even though this is for CSS same can be applied for js
HTH

Resources