Rails - load javascript function every server/client action - javascript

My rails app load application.js functions only when im refresh the page,in other case (site surfing,AJAX operations) it doesent.So how to load application.js every server-client actions?Every function pulled inside the
$(document).ready(function() {

$(document).ready(function() { will not work properly with Turbolinks enabled since it'll be triggered just once, you want to use this instead:
var ready;
ready = function() {
...your javascript goes here...
};
$(document).ready(ready);
$(document).on('page:load', ready);
See this link for more information: Rails 4: how to use $(document).ready() with turbo-links

Related

Rails Javascript compatible with Turbolinks

I need some help. I'm a beginner on this. My javascript doesn't seem to be loading after a user clicks on a link_to and I think the issue might be compatibility with Turbolinks. Any one can help me on this? Below is my script. Thanks in advance!
$(document).ready(function() {
// executes when HTML-Document is loaded and DOM is ready
console.log("document is ready");
$(".navbar-nav").clone().prependTo("#off-canvas");
$(function() {
$(document).trigger("enhance");
});
// document ready
});
$(window).load(function() {
// executes when complete page is fully loaded, including all frames, objects and images
console.log("window is loaded");
// window load
});
This solution suggested in another question doesn't work for me at all;
$(document).on('turbolinks:load', function() {
try changing the line: (document).ready(function() {
to: $(document).on('turbolinks:load', function() {
if you have already tried that and it does not work, you may need to reinitialize/load the js in the final js.erb file.
You can do this a few ways. Here is one:
Attach your javascript to the window so that it is globally available.
Call that function in your js.erb like this: Global.some_js_function();

Proper "Rails" way to perform javascript on specific pages

I'm attempting to run javascript on specific pages and my only solution seems like an anti-pattern. I have controller.js generated inside of assets/javascripts/. I'm using gem 'jquery-turbolinks' I have code resembling the following:
$(document).ready(function () {
//Initiate DataTables ect..
}
)
This code is firing on every page So I added the following inside of it.
if ($('#page-specific_element').length > 0) {
//Initiate Datatables ect.
}
My question being, is there a way to set rails to utilize only the javascript files necessary to a specific controller or is logic gating behind an element search the best solution?
This is a pretty nice turbolinks specific solution:
<body data-controller="<%= controller.controller_name %>" data-action="<%= controller.action_name %>">
// Instead of listening for document ready
$(document).on('users#show:loaded', function(){
$('#logger').append('<li>Users Show action loaded</li>');
});
// Instead of listening for document ready
$(document).on('users:loaded', function(){
$('#logger').append('<li>Some users controller method loaded</li>');
});
// Turbolinks fires "page:change" when it changes the page content.
// you could change this to just document ready if you are not using
// turbolinks.
$(document).on("page:change", function(){
var data = $('body').data();
$(document).trigger(data.controller + ':loaded');
$(document).trigger(data.controller + '#' + data.action + ':loaded');
});
// This is just for demonstration purposes...
$(document).trigger("page:change");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body data-controller="users" data-action="show">
<ul id="logger"></ul>
</body>
You should note that if you are using Turbolinks that you'll have a long-running, persistent session with maintained state. Which means that if you add inline script tags or load additional javascript files in your views they will linger in the browsers memory.
You therefore might therefore want to cleanup whatever page specific event handlers you have created on page:before-unload.
There are many ways to do this. I'll describe one.
I use this old gem to wrap all my .module.js files in commonjs modules.
I then have a helper that writes something like the following to a <script> tag in the head of every HTML page.
<script>
var App {
pageModule: 'posts/create'
};
</script>
posts/create is generated from a simplified mix of the current controller and action rendering the request.
I then have something like the following in my domready for my application.js.
try { App.pageModule = require(App.pageModule); } catch(e) { console.log('%c' + e, 'color:red; background-color:yellow'); }
if (_.isPlainObject(App.pageModule) && _.has(App.pageModule, 'initialize')) {
App.pageModule.initialize();
}
Finally, I'll have a file like this which is specific to the /posts/create URL.
app/assets/posts/create.module.js
module.exports = {
initialize: function() {
// data-tables stuff here...
}
}

$(document).ready does not work in Rails

I'm using a *.js.erb in my Rails-App, which reacts to a clicked Link.
But when I render my page, by getting there via a link_to, I have to refresh the Page, to make it work. Is there any Trick, how I can make this work?
Here is a very simplified version of my code:
$(document).ready(function(){
$('#toright').click(alert(">> was clicked"));
});
$(document).ready(function(){
$('#toleft').click(alert("<< was clicked"));
});
$(document).ready(function(){
$('#save').click(alert("save was clicked"));
});
$(document).ready(function() {
alert("The document is ready!");
});
After the site is rendered, it does not show my function, but when I type the URL into my address-bar, it works.
Some EDITS:
I'm using Rails 4.0.1
I have the js.erb in my assets folder
Ok. I've put them all in one $(document).ready, but I still have to reload my file for making my JS work.
UPDATE:
So I have edited my application.js to contain
$(document).ready(function(){
alert("The document is ready!");
$('#toright').click(alert(">> was clicked"));
$('#toleft').click(alert("<< was clicked"));
$('#save').click(alert("save was clicked"));
});
and put my js.erb to be only .js in my assets/javascripts folder.
But anyway, it just won't work until I have refreshed the page.
ready is a jQuery function, thus ensure you to use and include properly the jQuery library in your Javascript.
Furthermore, if you don't need to exchange data between your controller and your Javascript, I advice you to put your Javascript in your asset folder, for instance: /app/assets/application.js.
This is possible only for the Rails applications 3.x and 4.x.
Best regards.
Since the introduction of turbolinks in rails 4 you can use:
$(document).on('turbolinks:load', function() {
// Events
}
Instead of:
$(document).ready(function(){
// Events
}

Ruby on Rails 4 javascript not executed

I have a custom js file in app/assets/javascripts.
This is the js file:
//app/assets/javascripts/contacts.js
//$(document).ready(function() { //I've already tried with this method
$(window).load(function() {
alert("foo bar")
});
I require the file contacts.js file in the application.js file.
If I inspect the html page I see the js file loaded correctly, but the message is not shown.
If I reload the page (by pressing f5), the message is correctly show.
When the page is loaded the javascript is loaded (I can see it in source html code in the browser) but not executed.
Can you help me?
SOLUTION:
Rails 4: how to use $(document).ready() with turbo-links
$(document).ready(function() { } # Not working with turbo-links
From
Turbolinks overrides the normal page loading process, the event that
this relies on will not be fired. If you have code that looks like
this, you must change your code to do this instead:
$(document).on('ready page:load', function () {
// you code here
});
Another question
With Turbolinks version 5 (starting from Rails 5) you need to use:
$(document).on("turbolinks:load", function () {
// YOUR CODE
});

How to Hide an Element using Jquery and Coffeescript in Rails?

I would like to hide an element in a page on my Rails site, but I'm not yet that familiar with Jquery or Coffeescript.
This code works in the console:
$('#TheButton').click(function(){$('#TheText').toggle()});
I then converted it to Coffescript:
$("#TheButton").click ->
$("#TheText").toggle()
But it doesn't work on my Rails page. How do I fix it? Below is the generated javascript file:
(function() {
jQuery(function() {
# stuff...
});
$('form').on('click', '.add_fields', function(event) {
# stuff...
});
$("#TheButton").click(function() {
return $("#TheText").toggle();
});
}).call(this);
If your JS files are embedded at the top of your layout, every file you have must be wrapped in that jQuery call
jQuery's selectors don't work until after the page is loaded. You'll need to make sure your code runs after the document is ready:
$(document).ready ->
$("#TheButton").click ->
$("#TheText").toggle()
# other stuff you want to happen after document load
Add
$ ->
Before your code to ensure it runs after the DOM is loaded.

Categories

Resources