Search code examples
ruby-on-rails-3ujs

Using simple javascript and passing arguments with Rails3 and UJS


I have watched railscasts about unobtrusive javascript and read numerous tutorials, but two things about unobtrusive javascript in Rails3 still confuses me:

  1. End-point for simple javascript (hiding some elements, adding CSS class, ...)
  2. Passing arguments to JS

Let me clarify this with sample code. I want to make a link which fades out some element with id "sample":

link_to 'Fade sample', url, :remote => true

What should be the url so it can execute JS? Should it be new action in controller named for example 'javascript' so it can access JS in javascript.js.erb which contains:

$('#sample').fadeOut();

Also, second question about ujs is related with passing arguments to JS (timeout, for this example). I can write:

link_to 'Fade sample', url, :data-timeout => 1500, :remote => true

but don't know how to access data-timeout in javascript.

I am using Rails 3.0.5, JQuery 1.5.2 and jquery-ujs.


Solution

  • I would try to answer one by one.

    1. url in link_to. It would be a url hash for any resource in the application. Lets suppose you have specified resources :foos in the routes.rb, it will create 6 urls for CRUD operation. You can pass these to the urls by the methods like new_foo_url, foo_url(@foo) or foos_url. Even you can pass a hash manually like {:controller=>:foos_controller, :action=>:index}, also you can pass multiple parameters to the hash like {:controller=>:foos_controller, :action=>:index, :param1=>"value1", :param2=>"value2"}. Also you can pass strings urls like foos/new, foos/1 etc

    2. You can access custom tag attributes with jQuery very easily. for example you want to access anchor with id="link", you can $('#link').attr("data-timeout"). If you don't know what exactly the id is, but you know it have an attribute you can call $("a[data-timeout]").first().attr('data-timeout')