scientiffic
scientiffic

Reputation: 9415

onmouseover for link_to image_tag

I have a linked image_tag that I would like to change images on mouseover. I thought the following would work, but the image is not switching on mouseover:

<%= link_to image_tag("new_step.png"),new_project_step_path(@project), :class=> "newStep", :onmouseover => "new_step_highlighted.png"%>

I also tried editing the css, but this unfortunately didn't work either:

.newStep{
    background: url('../assets/new_step_highlighted.png');
}

.newStep:hover{
    background: url('../assets/new_step_highlighted.png');
}

For both cases, only the image "new_step.png" appears. How would I fix this? Thanks in advance for your help!

Upvotes: 5

Views: 6214

Answers (3)

Albert Catal&#224;
Albert Catal&#224;

Reputation: 2044

You can do it without modifying CSS, with less code:

<%= link_to some_route_path do
    image_tag("find.png", onmouseover: "this.src='#{asset_path('find_sel.png')}'", onmouseout: "this.src='#{asset_path('find.png')}'")
end %>

Upvotes: 9

Raindal
Raindal

Reputation: 3237

With css only, you need to have both images used as the background property of the link_to tag (actually the a tag). With what you wrote, you had one image "hard-coded" into the dom with an image_tag and you tried to change the link's background property cause newStep is actually the link_to class.

<%= link_to "Text", new_project_step_path(@project), :class => "newStep" %>

Then the css (btw, you don't need to prepend ".." to the path to your assets folder) :

.newStep {
    display: inline-block;
    width: your-image-width;
    height: your-image-height;
    background: url('/assets/new_step.png');
}

.newStep:hover {
    background: url('/assets/new_step_highlighted.png');
}

Here the fiddle: http://jsfiddle.net/km6Sp/

Upvotes: 8

scientiffic
scientiffic

Reputation: 9415

It turns out that Sparda's response was correct except that my image path was actually just "/assets/new_step.png". The images weren't appearing because of an issue with my CSS file.

Upvotes: 0

Related Questions