Gnatblack
Gnatblack

Reputation: 11

Change img src attribute on hover for multiple img tags

I wonder if anyone can help!? It's been a while since I've been on here so hope somebody can give me some pointers as I have hit a mental block!

I'm trying to change the src attribute for an image on hover which might not sound too difficult but I'm trying to do it for a number of components and write a function that will take care of them all at once so I don't have to repeat code!

I have done a fair bit of digging and in my head, this seems to make the most sense but it's not working! Can anyone see where I'm going wrong??

$(function(){
    $('img.natcard-img').each(function() {
        var image=$('img',this),
            offPng=image.attr('src'),
            onPng=offPng.replace(/-one\.(\w+)$/,'-two.$1');
            onImg=new Image();
        onImg.src=onPng;
        $(this).hover(
            function(){image.attr('src',onPng)},
            function(){image.attr('src',offPng)}
        )
    });
    
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://via.placeholder.com/140x100" alt="example 1" class="natcard-img">

From above, I'm using a naming convention for the images that should make it an easier swap ie. just amend the filename slightly in each case and I believe this should work on any file type jpg/png.

Many thanks for any pointers!

Upvotes: 0

Views: 74

Answers (2)

Benito
Benito

Reputation: 700

I tested it on my computer. In the console I had this error:

jquery-3.5.1.slim.min.js:2 Uncaught TypeError: Cannot read property 'replace' of undefined

I solved it by fixing the selector, replacing:

var image=$('img',this),

With this:

var image=$(this),

Inside $(...).each(function() { ... }), this is a DOM node, and you just need to wrap it with $() to get a jQuery object.

Upvotes: 1

charlietfl
charlietfl

Reputation: 171679

Just change var image=$('img',this) to:

var image=$(this)

What yours is doing is looking for an img that is a child of the current one ...which is not a real scenario

Upvotes: 0

Related Questions