Rails Jquery doesn't work on other pages - javascript

I believe jQuery doesn't work on other pages than the one you just installed. For example, when I type localhost:3000/, in the '/' directory all jQuery works. But when I click to a link created by Rails as
<%= link_to "Example Link", news_path %>
The page correctly loads, but the jQuery doesn't work. My jQuery codes are as stated:
$(function() {
console.log( "pageloaded" );
....
$('.up').click(function(){
.....
});
});

In Rails 4 turbolinks is active by default.
That means, that $(document).ready() is not executed, when you load a new page.
turbolink fires a new event page:load. You can use this to run your javascript code:
$(document).on('page:load', your_start_function);
There is an excelent rails cast on turbolinks

https://github.com/kossnocorp/jquery.turbolinks
This gem binds jQuery.ready function with Turbolinks listen event page:load, therefore the solution is supposed to be solved if you are using Turbolinks with Rails 4

You need gem 'jquery-rails' in your Gemfile (then bundle install if you're using bundler)
Once that's done, you need to require it in your application.js file:
//= require jquery
Last, you need to ensure that the application.js file is loaded as part of the application template. In application.html.erb you should have the following:
<%= javascript_include_tag "application" %>
I believe that this is all there by default in a Rails install so if you have removed any of these settings you'll need to add them back to get it to work.

Related

Rails .js.erb templates no longer work with Webpack

I've just switched my Rails app over to use WebPack to deal with assets etc. It's working well apart from I have some JS templates in my views directory (*.js.erb) . These require jQuery and as jQuery is pulled in as part of my WebPack bundles, it is not working in those templates.
Is there a way to allow those templates to work?
I got this to work in my app by adding the expose-loader package, then adding these two lines to my app/javascript/packs/application.js:
import 'expose-loader?$!jquery';
import 'expose-loader?jQuery!jquery';
Well in order to make things work you need to include jquery using yarn which works with the latest version of rails.
In Rails 5.1 this is done with the new JavaScript packet manager Yarn which you have to install first
sudo apt-get install yarn
Then you can use it to install jQuery:
yarn add jquery
To actually load jquery you have to add this line
//= require rails-ujs
//= require jquery
//= require turbolinks
//= require_tree .
After installing jquery your js.erb file will start working
Refer this article
This is how I use jquery in .js.erb when I use webpack and without asset pipeline.
(I assume that the Rails is created with something like $ rails new MyApp --webpack)
First of, I replace <%= javascript_include_tag 'application' %> with <%= javascript_pack_tag 'application' %> so we use javascript from /app/javascript/pack/application.js instead of /app/assets/javascripts/application.js
Add rails-ujs and jquery by running
$ yarn add rails-ujs jquery
modify /config/webpack/environment.js as following
const { environment } = require('#rails/webpacker')
const webpack = require('webpack')
// Add an additional plugin of your choosing : ProvidePlugin
environment.plugins.prepend(
'Provide',
new webpack.ProvidePlugin({
$: 'jquery/src/jquery',
jquery: 'jquery/src/jquery'
})
)
module.exports = environment
The webpack configuration is reference from here
I make a test page like this...
in /app/views/pages/index.html.erb
<div class="index">
<h1 class="index--title">Index Title</h1>
<div class="index--jquery-test">
<%= link_to "jquery test", pages_index_path, remote: true %>
</div>
</div>
and in /app/views/pages/index.js.erb it has following code, that will run jquery when the link is clicked
$(function(){
console.log('run <%= "JQuery" %> from .js.erb')
})
In /app/javascript/pack/application.js import Rails and call Rails.start() to allow the date-remote in the link to work and to make unobtrusive javascript to call index.js.erb file.
I also try to see if jquery from within pack/application.js file is also work by calling console.log to show a title text that I got from jquery selector $('.index--title').text()
import Rails from 'rails-ujs'
Rails.start()
$(function() {
console.log($('.index--title').text())
})
When run Rails app at, let say, http://localhost:3000/pages/index you should see the 'Index Title' in console windows of the browser. And when click the link you should see 'run JQuery from .js.erb' in the console windows. I hope it works for you.

javascript asset dosen't load in my html.erb page

I am using :
Linux Ubuntu 16.04
ruby 2.4.0p0;
rails 5.1.1
I am a begginner in rails and I have followed the Ruby on Rails 4 Essential Training in lynda.com in order to learn. I am now stuck at the loading js assets task.
I have created the "app/assets/javascripts/demo.js" file which contains the js function :
function jsRoar(name) {
alert('I am ' + name + '. Hear me roar!');
}
Then I have load this file in my manifest file "app/assets/javascripts/public.js"
//= require jquery
//= require jquery_ujs
//= require demo
After that I have added external include of js to my layout at "app/views/layouts/application.html.erb":
<%= javascript_include_tag "public" %>
In my controller I have included my layout by typing at "app/controllers/demo_controller.rb"
layout 'application'
And finally I have called my function by typing these js codes in my demo/index.html.erb :
<%= link_to('Roar', '#', :onclick => "jsRoar('Yassser');return true;") %>
<%= javascript_tag("jsRoar('Rails');")%>
After that i get "undefined function" in my chrome console and the alert doesn't appears .I have defined the function in the same html.erb and it works so it's not a problem of javascript i think.
I must mention also that, at first when i run my server, i have obtained a problem of assets compilation so I have fixed by adding this line in "config/initializers/assets.rb":
Rails.application.config.assets.precompile += %w( public.js)
I am available for more details.
Please help.
My problem was resolved after deleting the "demo.coffee" file.
I discovered that the my issue is derived from the fact that I have two files with the same name (but different extensions) "demo.js" and "demo.coffee". Since the Rails asset helpers treat coffescript and js files equally this is ambiguous.
So I have deleted the "demo.coffee" and all my problems are settled.
Thank you all mates.
Great thnx for #max with his reply in this post
I think this:
<%= javascript_tag("jsRoar('Rails');")%>
should be:
<%= javascript_include_tag("demo") %>
See if this code works in your view:
$(document).ready(function(){
jsRoar('Yassser');
})

Rails - jQuery not working in production with Heroku

I'm deploying a website with Heroku, though really struggling to get the jQuery firing when it goes live. Locally, all works fine.
I've had a play and haven't found any solution - it's all loading in the asset pipeline, shows as a source on the live page (albeit without working) and I've tried all of the solutions I've found on the web.
I've performed rake assets:precompile, have config.assets.compile = true and, thinking it might be a problem due to Turbolinks, installed the jquery-turbolinks gem.
With every change I thought I'd have this running, though nothing has affected the site's behaviour yet. Here's some code:
Gemfile
...
gem 'bootstrap-will_paginate'
gem 'bootstrap-sass'
# Use jquery as the JavaScript library
gem 'jquery-rails'
gem 'jquery-ui-rails'
gem 'jquery-turbolinks'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
...
Application.js
...
//= require bootstrap
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require jquery-ui
//= require turbolinks
//= require_tree .
...
Application.html.erb
<head>
<link href='http://fonts.googleapis.com/css?family=Slabo+27px' rel='stylesheet' type='text/css'>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
Home.js
var validBox = function(x, y){
...
});
};
var main = function(){
$('.toggle').click(function(){
$('.about-me').toggle();
});
//Carosel
$('.arrow-next').click(function(){
...
});
$('.arrow-prev').click(function(){
...
});
//Comments
$('.btn').click(function() {
...
});
$('.status-box').keyup(validBox('.status-box', '.name-box'));
$('.name-box').keyup(validBox('.name-box', '.status-box'));
$('.btn').addClass('disabled');
}
$(document).ready(main);
Could it be a problem with the $(document).ready(main); line? I've a feeling I've read somewhere jQuery doesn't always respond as the page isn't loading from scratch / 'ready' when using Turbolinks, though thought the addition of the relevant Gem would resolve this. I've also tried $(document).on('ready', 'page:change')(main); to run the function at other points, but to no avail.
Alternatively, I seem to remember there being some command line functions to better ensure the assets run when live though can't find anything relevant.
Any help would be GREATLY appreciated as I'm stumped with this one. I'm pretty new to this, so apologies if there are any glaring, amateur errors in amongst this (though that might mean a simple solution!).
Thanks in advance, Steve.
In my case, I found the answer here:
Bootstrap won't detect jQuery 1.11.0 - Uncaught Error: Bootstrap's JavaScript requires jQuery
The Java console was throwing up the error mentioned there, and after lord knows how much hunting, simply changing the order the js files were loaded made the difference.
Bootstrap after jQuery, everything works perfectly!!
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require turbolinks
//= require_tree .

Javascript files in Rails 3.1 Asset Pipeline

I've tested my Rails app's functionality by placing jQuery at the bottom of my home.html.erb file with simple script tags. Everything works fine until I attempt to utilize the Asset Pipleine in Rails 3.1 and place the script within app/javascripts/home.js.erb
Anyone know why I can't get the javascript to work outside of the home.html.erb file
you could add the script tag in the application.html.erb and you'll have jquery in all your pages.
you can add the script in this way: (you should add the jquery-1.7.min file in the folder app/javascript)
<%= javascript_include_tag 'jquery-1.7.min'%>
Don't put home.js.erb in app/javascripts but extract your jquery from home.js.erb and put in app/assets/javascripts/home.js
add config.assets.precompile += %w( *.js ) to config/environments/production.rb or in config/application.rb for global env (test/dev/prod)
than in app/assets/javascripts/application.js have
//= require jquery
//= require jquery_ujs
//= require_self
//= require_tree .
call it with javascript_include_tag "application" from the view
... and finally, don't forget to add gem 'jquery-rails' to your Gemfile and run bundle
As far as what I was looking to do, which was separate javascript files for different views, I was unsuccessful. I tried different naming conventions, etc.
What has worked for me however, is putting all of my javascript within application.js. Doing this makes this code accessible by every view throughout the entire application. Depending upon your needs and your app, you may want to put the script within [your-model-name].js.coffee which will make it accessible (I think just for your particular controllers and views). Since my app is a single model/controller setup, this is essentially the same thing.
Then, it's a matter of using selectors carefully as to not interfere with other pages unintentionally. In other words, if you want a piece of code to run within one particular view and not another, you will have to adjust your .js code accordingly, since everything within application.js is accessible to all views.

Load order with javascript_include_tag :all

So I've recently started to include quite a few .js files in to my web application and some of them depend on each other so load order is important.
However rails caching just seems to load a all.js file with no particular order to the files.
What's a good way to solve this issue?
You can do as follows
First, load the default JavaScript files.
Then load other scripts in the order that you want
<%= javascript_include_tag :defaults %>
<%= javascript_include_tag "script_1", "script_2", "script_3" %>
The load order depends on your Javascript manifest file. In Rails 3.1 you can go to
app/assets/javascripts/application.js
At the bottom of the file you will see directives for rails how what / how to include files into the Rake pipeline. In the below example, I included a new directive that will include all the files in the directory called "Templates". I also made sure that the Handlebars.js templating file is called before all of the files in the "Templates" directory, otherwise the browser would throw an exception
//= require handlebars
//= require_tree ../templates
//= require_tree .
Hope it helps!
I've been experimenting with the YUILoader Module, it seems pretty nifty, though I am currently frussing about loading up custom modules. It's totally doable, I just couldn't figure it out in 5 mins.
http://developer.yahoo.com/yui/yuiloader/ (YUI2.8.1)
http://developer.yahoo.com/yui/examples/yuiloader/index.html

Categories

Resources