Where do I put my JavaScript?

I’d like to include some simple JavaScript in my application that
registers an event handler (onclick) on a particular field in one of my
views and then calls a function to do some processing.

Where should I place the event handler and function code? In
application.js? Or in the layout that gets rendered with the view?

Thanks.

I’d like to include some simple JavaScript in my application that
registers an event handler (onclick) on a particular field in one of my
views and then calls a function to do some processing.

Where should I place the event handler and function code? In
application.js? Or in the layout that gets rendered with the view?

Kind of depends on where that view gets called from. If it’s just in
one
spot or if it’s a partial that gets included all over.

Also depends on whether your event handler is generic enough that it
could
be reused elsewhere.

Assuming it’s one view and quite specific, I would put the code in:

public/javascripts/controller_name/action_name.js

(replacing controller_name and action_name with the right values)

Then include that in your view…

The nice thing about this is that it makes it (somewhat) easier to see
what javascript (or CSS or images) go with what controllers/actions…

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs