Reputation: 2474
I'm having a problem with an image not changing on div hover using jQuery. Everything else changes accordingly except the image. Currently, the blue image stays the same and doesn't change. I also notice that the green image shows out of place when hovered which is weird. What am I doing wrong?
I created a jsfiddle problem here: https://jsfiddle.net/8bcfnd6f/
HTML:
<div id="widget">
<div id="text-button-widget">
<h2>Lorem Ipsum</h2>
<img id="widget-img" src="http://www.clipartbest.com/cliparts/di8/KRL/di8KRL8ie.png"/>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
</div>
CSS:
#widget:hover {
cursor: pointer;
background-color: #0098db;
}
jQuery:
$('#widget').hover(function(){ // hover in
$('#widget h2, #widget p').css('color','#fff');
$('#widget-img').css('background', 'url("http://www.clipartkid.com/images/17/youtube-play-icon-clipart-Ns7Pf4-clipart.gif") no-repeat center center fixed');
}, function(){ // hover out
$('#text-button-widget h2').css('color','#000');
$('#text-button-widget p').css('color','#000');
$('#widget-img').css('background', 'url("http://www.clipartbest.com/cliparts/di8/KRL/di8KRL8ie.png") no-repeat center center fixed');
});
Upvotes: 0
Views: 1947
Reputation: 4182
Right now, you code doesn't change the src, it just change BACKGROUND and add it to present src. If You just need to change src, you should use code like this:
$('#widget').hover(function(){ // hover in
$('#widget h2, #widget p').css('color','#fff');
$('#widget-img').attr("src", "http://www.clipartkid.com/images/17/youtube-play-icon-clipart-Ns7Pf4-clipart.gif");
}, function(){ // hover out
$('#text-button-widget h2').css('color','#000');
$('#text-button-widget p').css('color','#000');
$('#widget-img').attr("src", "http://www.clipartbest.com/cliparts/di8/KRL/di8KRL8ie.png");
});
Upvotes: 2
Reputation: 435
$('#widget-img').attr('src', 'http://www.clipartkid.com/images/17/youtube-play-icon-clipart-Ns7Pf4-clipart.gif')
Upvotes: 2
Reputation: 2701
if you completely want to change the <img>
you should set it's width and height to 0, and add padding accordingly. Then add the background image.
The CSS solution, as per your case. No Javascript needed.
#widget:hover {
cursor: pointer;
background-color: #0098db;
color: #fff;
}
#widget:hover img {
height: 0;
width: 0;
background: url("http://www.clipartkid.com/images/17/youtube-play-icon-clipart-Ns7Pf4-clipart.gif") no-repeat;
background-size: 256px 256px;
background-position: center center;
padding: 128px;
}
Upvotes: 1