开发者

Rails 3, using UJS on html area tag

When the user clicks on on area of an image I want to trigger and ajax request to the server. Is there an easy way to implement this a-la Rails 3 UJS? Something similar to link_to ..., :remote=>true?

I have tried to the following code:

#post_bar
  =image_tag 'post_bar_270x57.png', :usemap=>'#add_post'
  %map{:name=>"add_开发者_开发百科post"}
    %area{:shape=>"rect", :coords=>"40,4,86,50", :href=>new_message_path, :'data-remote'=>'true', :title=>"Message"}

but the added data-remote attributes does not work.

Thanks for any help.


After trying several things I concluded the easiest way is to to have an HTML anchor element on top of the png with that I can simply use the link_to helper with :remote=>true. It took me less than 10 minutes to get the all thing working.

Edit: here is the code form my haml file (in production I removed the map element)

#post_bar
  =image_tag 'post_bar_270x57.png', :usemap=>'#add_post'
  %map{:name=>"add_post"}
    %area{:shape=>"rect", :coords=>"40,4,86,50", :href=>new_message_path, :title=>"Message"}
    %area{:shape=>"rect", :coords=>"100,4,146,50", :href=>new_message_path, :title=>"Reminder(140 chars)"}
  #post_message_link
    =link_to "", new_message_path, :remote=>true

and the css

#post_message_link a{
    position: absolute;
    top: 0px;
    left: 40px;
    width: 45px;
    height: 50px;
    display: block;
    z-index: 100;
}


In the jquery-rails gem (path found with 'bundle show jquery-rails') there is a javascript file for jquery-ujs under vendor/assets/javascripts.

On line 51 you can see the following:

// Link elements bound by jquery-ujs   
linkClickSelector: 'a[data-confirm], a[data-method], a[data-remote], a[data-disable-with]'

I found adding the area tag to this line allows you to use UJS in the same way as you do for normal links, etc.

Ideally, you would make the code a bit better by adding another variable, but since this is just a hack I added it to the existing variables.

// Link elements bound by jquery-ujs   
linkClickSelector: 'a[data-confirm], a[data-method], a[data-remote], a[data-disable-with]', 'area[data-confirm]', 'area[data-method]', 'area[data-remote]',
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜