Reputation: 5644
Maybe an easy question, but what is good practice in Rails when you want to change an image when the mouse hover over the image (the image is not a link, just an image)?
Upvotes: 2
Views: 2577
Reputation: 32933
There are two ways to do this:
1) Use an img tag, and use javascript to change the img src attribute on hover
2) Use a div (or other non-img element), and show the image via the background
property, set in your css. You can then add an additional :hover
rule to show the alternate image on hover.
Note 1) - you can't do a "hybrid" approach of using css to change the background of the img tag, as the background of an image tag is behind the image, and so can't be seen: you'd be changing the "layer" behind the image
Note 2) - if you use js with an img tag, put the alternate image path in a data
attribute, eg "data-hover-src="/images/pic2.png"
. Then you can manage it with a simple standard javascript function.
Note 3) - if the image src is database-generated (eg it's for an image a user has uploaded), you can still do it by css, but you need to do it by putting the css into a style attribute on the element.
The decision on which path to go down is a little complicated, but could be boiled down to "if the images are content, eg that users have uploaded, use an img tag. If the images are part of the look and feel of your website, use css". However, you can use either approach in either situation with a bit of work.
See also: When to use IMG vs. CSS background-image? and Div Background Image or Using IMG Tag
Upvotes: 2
Reputation: 12320
Lets there is an image
<%= image_tag "image.jpg", id: "img" %>
Now in js using jQuery
$(function() {
$("#img")
.mouseover(function() {
var src = $(this).attr("src").replace("image.jpg", "over.jpg");
$(this).attr("src", src);
})
.mouseout(function() {
var src = $(this).attr("src").replace("over.jpg", "image.jpg");
$(this).attr("src", src);
});
});
Upvotes: 0
Reputation: 17834
Let's assume this is your a
tag, add a class and an id(if needed) to it
<%= image_tag "xyz.jpg", class: "change-image" %>
Now in js file
$(".change-image").hover(function(){
$(this).attr("src") = // url of the new image
});
Upvotes: 0
Reputation: 2034
Try this :
HTML:
<img id="demo_image" src="smiley.gif" alt="Smiley face" width="42" height="42" onmouseover="changeImage(this)" onmouseout="changeImage(this)" data-image2="http://mw2.google.com/mw-panoramio/photos/small/17287086.jpg">
JS:
function changeImage(img) {
img = $(img);
var in_url = img.attr('src'),
out_url = img.attr('data-image2');
img.attr('src', out_url).attr('data-image2', in_url);
}
Upvotes: 3