I just started to learn javascript and want to use it in Rails. The javascript code is very simple, mainly for experiment:
var pageAlert = function(){
alert("This is working");}
$('#refresh-button').on('click',pageAlert);
I must put the code in "application.js" file and inside the function
$(document).ready(function(){...});
Otherwise, it won't work. For example, if I put it in "custom.js" or in "application.js" but outside the document.ready function, not working. I assume I don't have to put everything inside the document.ready function. I know the concept of asset pipeline, and in the "application.js", I have the default
//= require_tree .
This should be easy, but I just can't figure it out. Any suggestion or tutorial on this? Thanks.
var pageAlert..part can be outside the$(document).ready...block, but the$('#refresh-button').on..part should be within the$(document).ready...as you want to make sure the element with idrefresh-buttonexists in the DOM before that JavaScript runs.$('#refresh-button').on..it searches for an element in the DOM with that ID and assigns the event handler to that element. If the DOM is still loading, and it doesn't find that element, then no event handler is assigned, and the click doesn't fire.$(document).readyblock or from some other event that is fired after the DOM is loaded.