sklrboy sklrboy - 2 months ago 9
HTML Question

Changing image file path on image:hover

I'm currently working on a portfolio website, where I have to insert a series of reference logos in a couple rows, just like:

<div class="row">
<div class="col-sm-2 reference">
<a href="#"><img class="img-responsive" src="img/logo section/final/faded/adelie.png" alt="Adelie"></a>
</div>
<div class="col-sm-2 reference">
<a href="#"><img class="img-responsive" src="img/logo section/final/faded/amageme.png" alt="Amageme"></a>
</div>
<div class="col-sm-2 reference">
<a href="#"><img class="img-responsive" src="img/logo section/final/faded/bakey.png" alt="Bakey"></a>
</div>
<div class="col-sm-2 reference">
<a href="#"><img class="img-responsive" src="img/logo section/final/faded/byensdepot.png" alt="Byensdepot"></a>
</div>
<div class="col-sm-2 reference">
<a href="#"><img class="img-responsive" src="img/logo section/final/faded/dialoogle.png" alt="Dialoogle"></a>
</div>
<div class="col-sm-2 reference">
<a href="#"><img class="img-responsive" src="img/logo section/final/faded/drachmann.png" alt="Drachmann"></a>
</div>
</div>


But when hovering over a logo, I'd like to change the file path, somehow like:

var fadedpath = "img/logo section/final/faded/";
var colorpath = "img/logo section/final/color/";
$(".reference").hover(function(){
$(this).attr(colorpath, filename);
}, function(){
$(this).attr(fadedpath, filename);
});


What is the correct syntax to do so? Because talking about multiple files, it's not effective to change it in css one by one.

Answer

Your code is almost correct however your user of attr() is incorrect. You need to use the getter to retrieve the current src and then replace() the values. You also need to change the attribute on the image within .reference, not on the .reference element itself. Try this:

var fadedpath = "img/logo section/final/faded/";
var colorpath = "img/logo section/final/color/";

$(".reference").hover(function(){
    $(this).find('img').attr('src', function(i, src) {
        return src.replace(fadedpath, colorpath);
    });
}, function(){
    $(this).find('img').attr('src', function(i, src) {
        return src.replace(colorpath, fadedpath);
    });
});

Also note that you shouldn't put spaces in folder names used in URLs.