user2004710
user2004710

Reputation: 187

Javascript/Rails - How to wrap link_to rather than <a></a> in javascript

I'm very new to rails and was using the jpages plugin for a concept. My javascript is as follows:

Javascript

$("ul#thumbs li").click(function(){
    $(this).addClass("selected").siblings().removeClass("selected");
    var img = $(this).children().clone().addClass("animated fadeIn");
    var linkValue = $(this).children("img").attr("alt");
    $("div.img").html( img ).wrap($('<a></a>').attr('href', linkValue));
});

HTML

<ul id="thumbs" class="clearfix">
    <li><img src="example1.jpg" alt="page1.html"></li>
    <li><img src="example2.jpg" alt="page2.html"></li>
    <li><img src="example3.jpg" alt="page3.html"></li>
</ul>

I want to be able to change this line:

$("div.img").html( img ).wrap($('<a></a>').attr('href', linkValue));

so that the wrap would be something like:

$("div.img").html( img ).attr(linkValue));

with the html being:

<li>
    <img src="example1.jpg" alt="page1_path">
</li>

There must be an easier way than to take the alt info and wrap in javascript with <%= link_to" at the beginning and do "%> at the end. Any help would be appreciated.

Upvotes: 1

Views: 200

Answers (2)

Michelle
Michelle

Reputation: 2712

If you are using Ruby on Rails, end your javascript file with .js.erb

Now you can include Ruby in your javascript. e.g...

$("#container").append(<%= link_to "Foo", root_path %>); 

If you need to access controllers or models (which I suspect you may need to), then calling ruby from your assets Javascript won't work.

You'll need to either write the javascript inline, as part of the HTML view, or create a javascript file that corresponds to a controller method, and call it from there. e.g.

In your Foo controller...

def some_method
  respond_to do |format|
    format.js
  end
end

In your Foo views, create a some_method.js.erb that contains all the javascript you need. The file will have access to your controller and model methods.

Upvotes: 0

codingrose
codingrose

Reputation: 15699

It is not possible.

When you write <%= in ruby, if you have ever observed, HTML markup never contains ruby tags i.e. <%=.

Here, you are inserting ruby tags via javascript, but ruby tags cannot be written on HTML. They need to be compiled first.

Better you following or something like that.

$("ul#thumbs li").click(function(){
    $(this).addClass("selected").siblings().removeClass("selected");
    var img = $(this).children().clone().addClass("animated fadeIn");
    var linkValue = $(this).children("img").attr("alt");
    $("div.img").html(img);
    $("div.img img").wrap($('<a></a>').attr('href', linkValue));
});

Upvotes: 3

Related Questions