I have an img tag that I want to change the src when hover and it all works but i would like to add some transition so it doesn't look so rough but since it's an img src i cant target it with css.
http://jsfiddle.net/Ne5zw/1/
html
<img id="bg" src="img/img1.jpg"> <div onmouseover="imgChange('img/img2.jpg'); "onmouseout="imgChange('img/img1.jpg');">
js
function imgChange(im){ document.getElementById('bg').src=(im); }
To make the image transition with a fading effect we use the asynchronous function. Inside the asynchronous function, use another setInterval() method to slowly decrease the opacity of the topmost image till opacity becomes 0.
The solution is actually quite simple using JavaScript. To trigger an element's transition, toggle a class name on that element that triggers it. To pause an element's transition, use getComputedStyle and getPropertyValue at the point in the transition you want to pause it.
You can change an HTML image src attribute programatically by using JavaScript. First, you need to grab the HTML element by using JavaScript element selector methods like getElementById() or querySelector() and assign the element to a variable.
The required src attribute specifies the URL of an image. Note: The src property can be changed at any time. However, the new image inherits the height and width attributes of the original image, if not new height and width properties are specified.
You want a crossfade. Basically you need to position both images on top of each other, and set one's opacity
to 0 so that it will be hidden:
<div id="container"> <img class="hidden image1" src="http://www.istockphoto.com/file_thumbview_approve/4629609/2/istockphoto_4629609-green-field.jpg"> <img class="image2" src="http://www.istockphoto.com/file_thumbview_approve/9958532/2/istockphoto_9958532-sun-and-clouds.jpg" /> </div>
CSS:
.hidden{ opacity:0; } img{ position:absolute; opacity:1; transition:opacity 0.5s linear; }
With a transition
set for opacity
on the images, all we need to do is trigger it with this script:
$(function(){ debugger; $(document).on('mouseenter', '#hoverMe', function(){ $('img').toggleClass('hidden'); }); });
http://jsfiddle.net/Ne5zw/12/
Here is a pure css solution using css transition
. You can use a div
as the container and set the background-image
on hover.
.image-container { background: url(http://placeholder.pics/svg/300x300/DEDEDE/555555/Old%20Image) center center no-repeat; background-size: contain; width: 150px; height: 150px; -webkit-transition: all .3s ease-in-out; -moz-transition: all .3s ease-in-out; transition: all .3s ease-in-out; } .image-container:hover { background-image: url("http://placeholder.pics/svg/300x300/DEDEDE/555555/New%20Image"); }
<div class="image-container"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With