Reputation: 265
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.
Upvotes: 0
Views: 65
Reputation: 3540
You can put code like function declarations and basic javascript outside $(document).ready(function(){...});
block. Try for example to just write alert("Hello world")
.
However $(document).ready(function(){...});
will first be triggered when the DOM is loaded, ie. when your browser have downloaded the HTML and are ready to render the page. If you call javascript functions that manipulate the DOM like $('#refresh-button')
outside of the ready
block, will the code be runned before the DOM is ready, and will most likely not work because, like in this example, there is no element with the id refresh-button
yet.
Hope this answers your question, otherwise feel free to ask for more information.
Upvotes: 1