Reputation: 531
I am creating a hover effect using jQuery and data-attribute.
So what I did is that I put some data attribute on each images and then I access them via jQuery and store them in a variable. Then I access them to change the image via jQuery. However, I have no idea how to put it back to the original on "mouseout"
Here's my jQuery:
$(document).ready(function(){
$('img').hover(function(){
var s = $(this).attr('data-alt-src');
$(this).attr('src', s);
}, function(){
$(this).attr('src');
});
});
Any idea?
Upvotes: 3
Views: 119
Reputation: 3308
$(document).ready(function() {
var src_original;
$('img').hover(function() {
src_original = $(this).attr('src');
var s = $(this).attr('data-alt-src');
$(this).attr('src', s);
}, function() {
$(this).attr('src', src_original);
});
});
img {
cursor: pointer;
}
img:hover {
opacity: 0.7;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<img src="http://goo.gl/osWLNm" data-alt-src='http://goo.gl/K5yFHa' />
<img src="http://goo.gl/umj4bX" data-alt-src='http://goo.gl/bz4jQH' />
<img src="http://goo.gl/W1fumF" data-alt-src='http://goo.gl/d4gynn' />
<img src="http://goo.gl/wMb04Z" data-alt-src='http://goo.gl/LqZU0Q' />
</section>
Upvotes: 1
Reputation: 868
I added data-old-src to store default img source and load on mouse out.
Check https://jsfiddle.net/jzxh1asx/6/
HTML
<section>
<img src="http://goo.gl/osWLNm" data-old-src="http://goo.gl/osWLNm" data-alt-src='http://goo.gl/K5yFHa' />
<img src="http://goo.gl/umj4bX" data-old-src="http://goo.gl/umj4bX" data-alt-src='http://goo.gl/bz4jQH' />
<img src="http://goo.gl/W1fumF" data-old-src="http://goo.gl/W1fumF" data-alt-src='http://goo.gl/d4gynn' />
<img src="http://goo.gl/wMb04Z" data-old-src="http://goo.gl/wMb04Z" data-alt-src='http://goo.gl/LqZU0Q' />
</section>
JS
$(document).ready(function(){
$('img').hover(function(){
var s = $(this).attr('data-alt-src');
$(this).attr('src', s);
}, function(){
var os = $(this).attr('data-old-src');
$(this).attr('src', os);
});
});
Upvotes: 0
Reputation: 9637
To store current src as a variable and use it
var old="";
$(document).ready(function(){
$('img').hover(function(){
old=$(this).attr('src');
var s = $(this).attr('data-alt-src');
$(this).attr('src', s);
}, function(){
$(this).attr('src',old);
});
});
Upvotes: 1
Reputation: 133403
Store original image src
in cache using .data()
.
$(document).ready(function () {
$('img').hover(function () {
var that = $(this);
that.data('or-src', that.prop('src'))
that.prop('src', that.data('alt-src'));
}, function () {
var that = $(this);
$(this).prop('src', that.data('or-src'));
});
});
Upvotes: 0
Reputation: 10683
try to set origional src to other attribute and use that when mouseleave.
$(document).ready(function(){
$('img').hover(function(){
var s = $(this).attr('data-alt-src');
$(this).attr('orSrc',$(this).attr('src')).attr('src', s);
}, function(){
$(this).attr('src',$(this).attr('orSrc'));
});
});
Upvotes: 2