Loading JavaScript in Rails App - javascript

I'm trying to initiate a JS file when clicking on a link "link_to" in my rails app.
I ensured the the asset pipeline is working correctly by testing with
$(document).ready(function() {
alert("test");
});
and the alert popups without a problem.
However, the script only loads when I refresh after the page is loaded. I've tried the code below without any luck but as I said, it works once the page is reload.
var ready;
ready = function() {
//My JS Code
};
$(document).ready(ready);
$(document).on('page:load', ready);
I have the Turbolinks gem file complied Gem file below
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require bootstrap-sprockets
//= require jquery.slimscroll
//= require app
//= require zopim
//= require turbolinks
I'm sure it's something small I'm missing. I've seen examples using coffee script but I don't know enough about it to use it at this time.
Edit:
While monitoring Network under Chrome Dev tools, I noticed that none of the JS load until I hit F5 to reload the page but I don't seem to have problems with the other scripts. This might be a separate issue.

maybe try this ?
$(document).on('turbolinks:load', ready);

$(document).on('turbolinks:load', function() {
//My JS Code
})
This should work for you.

Related

rails + jquery - errors on every page but it still works (sometimes)

I am working on a rails app. It is a standard app, using server rendered pages, and jquery. I have had a decently hard time wrangling together the jquery and i am not sure why.
I am using jquery for a couple things: a datepicker and a timepicker. That is only used for a form a user can use, and is rendered in a users section where they can create/edit.
The structure of my javascript is right now i am using 1 javascript file called main which is required in my application.js. That is all the JS i am using.
application.js
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require bootstrap.min.js
//= require jquery.raty.min.js
//= require jquery.turbolinks
//= require chosen-jquery
//= require turbolinks
//= require main
//= require_tree .
main.js
$(document).ready(function() {
// users profile stuff
if ($('table.calendar tbody tr td ul').hasClass('active-trip')) {
$('.active-trip').parent().css('background-color', 'orange');
}
$("#trip_start_date").datepicker({
minDate: 1
});
$("#start_date").datepicker({
minDate: 1
});
$("#end_date").datepicker({
minDate: 1
});
// ==========
// js in user's trips
$('#trip_start_time').timepicker();
$('#trip_end_time').timepicker();
// ===========
});
The problem that I am having is I am using a bootstrap navbar, with some JS effects on it (dropdowns). On this one page (a resource called "Gyms", or /gyms) the JS completely breaks and leaves the navbar useless. The error that I am getting is
Uncaught TypeError: $(...).timepicker is not a function
And I notice when I get that error once, it then starts repeating and I get it on every page. But yet, when I go back to the form where i use this code, it works completely fine even with the error?
This might be a turbolinks issue, but I am really not sure. I am using these gems
gem 'jquery-rails'
gem 'jquery-ui-rails'
gem 'turbolinks'
gem 'jquery-turbolinks'
if that helps anything. I have also played around with using the jQuery CDN script rendered in application.html.erb but that doesn't really seem to help or hurt anything and is pretty much neutral. Any help would be much appreciated
Try changing the order of requiring:
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//
// ... your other scripts here ...
//
//= require turbolinks
put jquery.tubolinks before all other scripts but right after jquery

Why isn't Rails acknowledging relative JavaScript files?

app/assets/javascripts/application.js:
//= require jquery
//= require jquery_ujs
//= require_tree .
//= require bootstrap.min
app/assets/javascripts/economy.js:
$(document).ready(function() {
console.log("loaded file");
});
app/views/economy/index.html.erb:
<%= javascript_include_tag "economy" %>
app/config/initializers/assets.rb:
Rails.application.config.assets.version = '1.0'
Rails.application.config.assets.precompile += %w( economy.js )
Why doesn't economy.js print anything to the console when a page in my app is loaded?
I tried adding //= require economy.js but that didn't change anything, and should be redundant if I understand how require_tree works.
You're right that it should be automatically included.
The only thing that jumps out, given this level of detail, is that you have //= require bootstrap.min in there and a require should never have a file extension. It may be breaking all the requires. Change that to //= require bootstrap or for the sake of testing economy.js loading or remove it entirely for now.
If that doesn't work, here's a few things to try:
Try an alert("loaded file"); in case there is an issue with you browser console.
Try adding //= require economy without the .js.
Check the browser's sources to see if the file got loaded to narrow down the issue.
Also, don't forget to close your $(document).ready call with a ; at the end of }).
I found the answer. My app/assets/javascripts folder had a file called economy.coffee (for some reason?!), and all I had to do was remove it. I think it was overwriting my js file or something.

Rails turbolinks issues with window.onload

I have rails application with baguetteBox library for image popup effect, but it works properly only after page refresh.
I know that its because of turbolinks so I installed jquery-turbolinks gem but it still doesn't work. //require jquery.turbolinks is in the right spot.
//
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require baguetteBox.min
//= require turbolinks
//= require_tree .
And i have this piece of code in the bottom of show view
<script>
window.onload = function() {
baguetteBox.run('.step_div');
};
</script>
to initialize the script.
Any ideas?
You need to trigger things slightly differently for turbolinks:
var myFunc = function() {
baguetteBox.run('.step_div');
};
$(document).ready(myFunc);
$(document).on('page:load', myFunc); // Classic Turbolinks
$(document).on('turbolinks:load', myFunc); // Turbolinks 5
This way, your function will be called on a standard page ready trigger, and also when turbolinks loads the page into memory without an actual page refresh.
Obviously, you only need to include the turbolinks event trigger for the appropriate version of turbolinks that you're using.
Have a look here for the other events triggered by turbolinks 5: https://github.com/turbolinks/turbolinks#full-list-of-events
For the original turbolinks, the documentation is here:
https://github.com/rails/turbolinks/#events

Compiled Javascript not Working in Production Mode

I am building an app on my local machine. When I precompile and run it in production mode, the compiled javascript stops working. Specifically, I have javascript in one coffeescript file and application.js, both in the assets folder. All other javascript (i.e. jquery in ajax forms, etc) continues to work, which is why I think it must have to do with compilation.
Here is my application.js file:
//= require jquery
//= require jquery_ujs
//= require jquery-ui/autocomplete
//= require jquery-ui/dialog
//= require autocomplete-rails
//= require dresssed
//= require raphael
//= require morris
//= require best_in_place
//= require_tree .
$('.label-stock-health').popover({ html : true});
$(document).keypress(function(e) {
if ($('.search-bar').length){
if($(".search-bar").is(":visible")) {
} else {
$(".search-bar").show();
$("#q_name_cont").focus();
}
}
});
$("#spinner").hide();
$(document).ajaxStart(function() {
$("#spinner").fadeIn('slow');
}).ajaxStop(function() {
$("#spinner").hide();
});
$(document).ready(function() {
$(".show-search").click(function(){
if ($('.search-bar').length){
$(".search-bar").toggle();
}
});
$(".best_in_place").best_in_place();
});
This functionality still works in development mode. Additionally, if I hard code the javascript into my layout template, it will work. But without the hardcoding, it does not.
Any advice on what might be the culprit? If not , what is the best way to go about debugging this?
UPDATE #1
The only two errors I am seeing in the Javascript console of Chrome developer tools are posted below. They also show on my localhost development instance, where my javascript functionality is working in full.
Uncaught Google Maps API is required. Please register the following
JavaScript library
http://maps.google.com/maps/api/js?sensor=true.(anonymous function) #
application-6ab26aa5fc5d647a3b5543af7c9838a6.js:9t.(anonymous
function) #
application-6ab26aa5fc5d647a3b5543af7c9838a6.js:9(anonymous function)
# application-6ab26aa5fc5d647a3b5543af7c9838a6.js:9 variants:565 GET
http://www.example.com/bootstrap/glyphicons-halflings-regular.woff2
404 (Not Found)
I did wrote to you in upwork.com how ever here it is... If it is working in local host but when uploaded online stops working than it is permissions problem. I have encounter same problems in godady and blue host. Try playing with permissions. For (on blue host) worked permissions to be set at 5 5 4. or 5 5 5 I did not remember correctly. How ever delete all and reupload with new permissions once you figure out what they should be.
The culprit here is the popover line, you will need to include the popover plugin if you want to use it. Comment it out and deploy your code, it will start working again.
I've just sent you a message on upwork as well, but you should check if removing turbolinks from your application.js files resolves the issue:
//= require jquery
//= require jquery_ujs
//= require turbolinks ** remove this line as turbolinks interferes with javascript occasionally.
//= require_tree .
Please include another file name custom.js and updated
$(document).ajaxStart(function() {
$("#spinner").fadeIn('slow');
});
$(document).ajaxStop(function() {
$("#spinner").hide();
});

JavaScript not loading on production site with Safari

JavaScript works fine both locally and production on Chrome, but when I try in Safari, it doesn't. I would think the solution would be to enable JavaScript on Safari, but I do have it enabled, and it's working locally on Safari. It just doesn't work on production. I would think there's a problem with how I'm pushing up to production, but my production environment is working on Chrome.
I'm using Rails with jQuery Turbolinks.
My application.js:
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require bootstrap
//= require social-share-button
//= require zeroclipboard
//= require google_analytics
//= require turbolinks
//= require_tree .
A sample JS file that isn't loading correctly:
$(document).ready(function() {
var referLinkClip = new ZeroClipboard($("#referral-text-button"))
var referCodeClip = new ZeroClipboard($("#referral-code-button"))
var embedClip = new ZeroClipboard($("#embed-text-button"))
alert('foobar');
$(".copy-button").hover(function(){
$(this).css('background-color', '#7b7b7b');
}, function(){
$(this).css("background-color", '#949494');
});
$(".copy-button").click(function(){
$(this).css('outline', 'none');
$(this).css('background-color', '#2d3538');
setTimeout(function(){
$(this).css('background-color', '#949494');
}, 100);
});
});
My view using this JS (HAML):
%button#referral-code-button.plan-show.round-corners-8px.col-md-2.referral-links.copy-button{:'data-clipboard-target'=>'referral-code'}
Copy code
.plan-show.round-corners-8px.col-md-8.referral-links.light-text
Your affiliate code:
%span#referral-code.medium-text= "#{current_user.affiliate_code}"
This all works fine in Chrome locally and on production, but just not on production in Safari. I've compiled my assets with bundle exec rake assets:precompile, and it makes no difference.
Any ideas? I'm stumped.
Edit:
More info that may prove useful... Recently, even on Chrome, I've had trouble getting the JS to load properly unless the page is refreshed. In the JS file I provided, the $(".copy-button").click function works (button changes color), but neither the $(".copy-button").hover works, nor do the ZeroClipboard objects initialize. I'm including the JS in my application.html head, with =javascript_include_tag 'application'
I encountered a similar issue (see Safari iOS not loading Javascript file?) and found that the reason was Safari automatically sandboxing (blocking all JS execution) on requests done using HTTP/0.9.
For more details check out my answer in the other thread.

Categories