Insert javascript call inside <body onLoad = function ()> in RAILS

I'm n00b on the rails. The question is very simple, I want to know how I can call the javascript function call inside the body tag in the onLoad event.

I ask about this because in the representations I cannot find the body or head tag (it is as if they were created elsewhere).

thanks

+2
javascript ruby-on-rails onload onload-event
source share
3 answers

You do not need to modify the body tag to associate Javascript with the onload function. Instead of using the onload attribute in the body, you can assign the window.onload function inside an external Javascript file.

There are more advanced ways to use event listeners to perform the same function (launching a function when the page loads), which would add several listener functions or trigger functions to the DOM, a little or some time before the page loads. Just setting window.onload is the easiest way and your Javascript will be unobtrusive.

+4
source share

The body and head tag is usually defined in one of the layouts. The default app/views/layouts are located in app/views/layouts .

+2
source share

Eric Breschemer and Mlyaka are both correct.

Another approach (if you need to add custom elements to the header / footer specified for each view, you need to do something like this with yield blocks

Here is an example that allows you to override the title for each page, but the same method applies to customizing the script tags in the HTML header tag.

app/views/layouts/posts_layout.html.erb

 <html> <head> <title><%= yield(:page_title) || "My awesome site"%></title> </head> <body><%= yield %> </body> </html> 

app/views/posts/index.html.erb

 <%= content_for :page_title, "post listing" %> <h1>Here are your posts...</h1> 
+2
source share

All Articles