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
}
Related
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();
I've got an ASP.NET MVC app and I'm trying to use this Masked Input Plugin to mask/hint at dates. If I put this script in the #section Scripts{} at the bottom of the page, it functions just fine.
<script type="text/javascript">
$(document).ready(
function() {
$(function($) {
$(".datemask").mask("99/99/9999", { placeholder: "mm/dd/yyyy" });
});
});
</script>
But if I try to put it in a separate script file in the Scripts folder, so it runs on all pages, it never seems to run. I have another script running from the Scripts folder to add the jQuery date picker to my date fields:
$(document).ready(function() {
$(":input[type='datetime']").each(function() {
$(this).datepicker();
});
This script runs just fine on every page (it's loaded from the _Layout.cshtml partial view). But when I put my masking script in that file, whether part of the existing .each function, part of the existing .ready function, or in it's own .ready section, it never masks the textbox.
Is this something quirky about the Masked Input Plugin, or am I missing something about using JavaScript in MVC?
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...
}
}
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
});
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.