Reputation: 35
On a site with a lot of images I would like to add a mouseover event on each of them.
I could do it like this:
<img class="brand"
src="img/brands-grey/image1.svg"
onmouseover="this.src='img/brands/image1.svg';"
onmouseout="this.src='img/brands-grey/image1.svg';"/>
<img class="brand"
src="img/brands-grey/image2.svg"
onmouseover="this.src='img/brands/image2.svg';"
onmouseout="this.src='img/brands-grey/image2.svg';"/>`
But I rather would remove/insert "-grey" onmouseover/out from the src. Could some one point out to me how to accomplish this?
Thanks in advance!
Upvotes: 0
Views: 40
Reputation: 74420
You could just use CSS pseudo class :hover
and use any wrapper containing two images, this would have better behaviour in all cases:
HTML:
<span class="img-container">
<img class="brand" src="img/brands-grey/image1.svg"/>
<img class="brand-over" src="img/brands/image1.svg"/>
</span>
<span class="img-container">
<img class="brand" src="img/brands-grey/image2.svg"/>
<img class="brand-over" src="img/brands/image2.svg"/>
</span>
CSS:
.brand-over {
display: none;
}
.img-container:hover .brand-over {
display: inline;
}
.img-container:hover .brand {
display: none;
}
Now if brands-grey
is just an grayed out image, you even don't need two different images, just use e.g opacity: 0.4;
and on image over set opacity to 1. jsFiddle
Or using CSS3 filter with transition: jsFiddle
Upvotes: 0
Reputation: 24276
You put jQuery as a tag so here is a jQuery solution:
$(document).ready(function(){
$('img.brand').mouseenter(function(){
$(this).attr('src', $(this).attr('src').replace('-grey', ''));
}).mouseleave(function(){
$(this).attr('src', $(this).attr('src').replace('brands', 'brands-grey'));
});
});
The HTML will be much cleaner:
<img class="brand" src="img/brands-grey/image1.svg" />
<img class="brand" src="img/brands-grey/image2.svg" />
Instead of using 2 sets of images I would use an existent jQuery plugin like jQuery.BlackAndWhite.
Upvotes: 2
Reputation: 899
Try this
<img class="brand" src="img/brands-grey/image1.svg" onmouseover="this.src='img/brands/image1.svg';" onmouseout="this.src='img/brands-grey/image1.svg';"/>
<img class="brand" src="img/brands-grey/image2.svg" onmouseover="this.src='img/brands/image2.svg';" onmouseout="this.src='img/brands-grey/image2.svg';"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
jQuery(function(){
jQuery('img.brand').hover(function(){
// this function will be called when the mouse in
var src= $(this).attr('src');
src.replace('brands-grey', 'brands') ;
$(this).attr('src', src);
},
function (){
// mouse out handler
var src= $(this).attr('src');
src.replace('brands', 'brands-grey');
$(this).attr('src', src);
}
)
})
</script>
Please correct the the jquery path path. Here we used the jQuery hover method. And jsut implement the logic of add/remove gray part from the src as you asked.
Upvotes: 1