Reputation: 42
I'm building an employee bios page where the client wants selected thumbnails to display in color at full opacity and all others at lower opacity in black and white. Which wouldn't be hard - the trouble is, every thumbnail has to have a color state and a black and white state. So my next thought was to swap out the black and white image (which would be resting within the div with a color background image) on mouseover.
$('.thumbnail').mouseenter(function(){
var current = $(this); // cache thing
var thishtml = current.html(); // get contents of thing
current.html('').mouseleave(function(){ //empty the thing
current.html(thishtml); //put the variable back in the thing
});
});
My HTML would be as follows:
<div class = "thumbnail" style = "background-image: url(color.jpg);">
<img src="blackandwhite.jpg" />
</div>
Obviously, since I'm asking the question, my idea didn't work. The mouseover removes the innerHTML, and the variable is converted successfully, but it doesn't get inserted into the DIV again. What am I missing?
Upvotes: 0
Views: 98
Reputation: 4449
Why not trying using the show and hide methods? Be sure to specify a width for the containing divs, or the entire thing will disappear when hiding or showing. I'm guessing the thumbnails are all the same size, so it will be easy to add CSS such as:
CSS:
.thumbnail
{
width: 100px;
height; 100px;
}
Javascript
$(document).ready(function()
{
$('img', '.thumbnail').hide();//Start off hidden
$('.thumbnail').mouseenter(function()
{
$('img', this).show();
});
$('.thumbnail').mouseleave(function()
{
$('img', this).hide();
});
});
Upvotes: 0
Reputation: 5475
Try using .show() and hide() to make the blackandwhite.jpg image visible and hidden respectively.
$(".thumbnail").hover(
function () {
$(this).children("img").hide(); //hide b and w on mouse in
},
function () {
$(this).children("img").show(); //showb and w on mouse out
}
);
Upvotes: 0
Reputation: 15365
You don't need any Javascript to do that, just a piece of CSS:
div.thumbnail {
background-image: url(blackandwhite.jpg);
opacity: 0.7;
}
div.thumbnail:hover {
background-image: url(color.jpg);
opacity: 1;
}
Upvotes: 0
Reputation: 114367
Instead of swapping HTML use css.
CSS:
.hidden {
visibility:hidden
}
JS:
$(".thumbnail").hover(
function () {
$(this).find('img').addClass('hidden')
},
function () {
$(this).find('img').removeClass('hidden')
}
);
Upvotes: 2
Reputation: 69905
When you empty the html
there is nothing on which your mouseleave
event will fire to set the html
back again.
Working demo. In this demo I am just setting a character show that you can see the event getting fired, remove the character, it won't work.
Upvotes: 0