a simple image_tag rollover for Rails 4

In Rails 3.x you used to be able to do

1
< %= image_tag("mouse.png", :mouseover => "/images/mouse_over.png") %>

but that no longer works in Rails 4 🙁

For a simple and naive way to swap out a image on mouse hover (assuming you have a mouse!) in Rails 4+ :

1
2
3
4
5
< %= link_to image_something_clever_path(image.id) do %>
   < %= image_tag image.image.url(:thumb),
        onMouseover: "this.src='#{image_path(image.image.url(:medium))}'",
        onMouseout: "this.src='#{image_path(image.image.url(:thumb))}'" %>
< % end %>

this generates the correct code to insert on the medium size image when you hover with a mouse (onMouseover), assuming you Paperclip configuration generated an image with that handle, and swaps back out (onMouseout) the thumbnail image you where showing by default.

This also shows the code wrapper to create a href link to somewhere else to do something else clever.

there is another 2 ways to do the same thing, but in a more unobtrusive javascript or unobtrusive css way, is to toggle the images with javascript (jquery) with the images defined by embedded ruby in a similar manner; equally you could use some in-line css and a :hover event to replace the image (defined by embedded ruby in a similar manner);

Of course if you are looking to do a button or button styled link the more modern way is with Font-Awesome Icons or GLYPHICONS and the implentation would be something like (adpapted from the Bootstrap 3 Components Glyphicons Examples) :

1
2
3
< %= link_to something_clever_path(@something_clever), class: 'btn btn-success' do %>
     <span class="glyphicon glyphicon-star" aria-hidden="true"></span> Star
< % end -%>

Leave a Reply