Duplicate JavaScript Functions

Good afternoon,
I’m new to writing JavaScript, but I’m trying to get a function to work for GIFs where a static image sits in the place of the GIF on page load but upon mouse rollover (and hover) the GIF plays in the same spot. I got it to work on a test page using the following code:

Body:

<img id="img1" src="image1.jpg" />

JavaScript:

$(document).ready(function ()
{
    $("#img1").hover(
        function()
        {
            $(this).attr("src", "image1.gif");
        },
        function()
        {
            $(this).attr("src", "image1.jpg");
        }
     );
});

My problem is that I want to be able to use this function for multiple GIFs on a single page. So instead of one image1.jpg/image1.gif pairing I’d like to have an image2.jpg/image2/gif pairing in a different spot on the page, using the same hover function. Simply repeating the above code doesn’t work, and I think I have to do something with naming the function but I’m not quite sure how to do that.

So with that goal in mind, what should the code look like for using multiple images? Any example would be great, since I plan on using these functions many times on my site and having something to copy and paste day-to-day would be invaluable.

Thank you.

Hey Superfly,

Try this:

$(".gif-swap").hover(
    function() {
        var name = this.src.substr(0, this.src.lastIndexOf('.'));
        this.src = name + '.gif';
    },
    function() {
        var name = this.src.substr(0, this.src.lastIndexOf('.'));
        this.src = name + '.jpg';
    }
);

All you need to do is give your images the class ‘gif-swap’:

<img class="gif-swap" src="image1.jpg" />

Note that if you’re going to apply this behavior to a lot of images, or if you’ll be dynamically adding images to the page via ajax, then you’d be better off doing thiis:

$('body')
    .on('mouseenter', '.gif-swap', function() {
        var name = this.src.substr(0, this.src.lastIndexOf('.'));
        this.src = name + '.gif';
    })
    .on('mouseleave', '.gif-swap', function() {
        var name = this.src.substr(0, this.src.lastIndexOf('.'));
        this.src = name + '.jpg';
    }
);

which delegates the event handling to the body element, rather that attaching to each image.

Couldn’t get this to work. I tried this code:

<img class="gif-swap" src="image1.jpg" />
$(document).ready(function ()
{
$(".gif-swap").hover(
    function() {
        var name = this.src.substr(0, this.src.lastIndexOf('.'));
        this.src = name + 'image1.gif';
    },
    function() {
        var name = this.src.substr(0, this.src.lastIndexOf('.'));
        this.src = name + 'image1.jpg';
      }
   );
});

I’m sure I’m making some silly mistake, but I have no idea what it should be. Didn’t know if I need the (document).ready text in there, but I tried it with and without that text and it didn’t work.

The problem is that you’ve got this:

this.src = name + 'image1.gif';  // will set image src to 'image1image1.gif'

rather than this:

this.src = name + '.gif';  // will set image src to 'image1.gif'

To make the code reusable, it extracts the image name (minus the extension) from the current image source, and then changes the extension to .gif (or .jpg on mouseleave). If you hard code the name ‘image1.gif’ in there, it won’t work for any of the other images on the page.

As long as your JS goes just before the closing </body> tag, you don’t need to wrap it in a document ready function.

I think I just answered my own question. I’ll let you know if I get it to work.

My page did not like that at all. When I hovered over the .jpg, the images just flashed for a moment and then disappeared. I’m sure the files are in the correct locations, since it works with the code I used in the original post. Does that problem sound familiar?

Are you getting any errors in your browser’s console?

Not that I can tell. Everything else seems to be functioning as normal.

I’ll note that the image doesn’t disappear, it just turns into one of those broken-image icons you see when an image can’t be loaded. But that’s only after it flickers for a second or so.

Since it’s a gif, could the issue be that it isn’t loading on page load? Don’t know why that would be a problem.

Could you post the code for your page here (preferably the entire page), or provide a link to it if it’s online, so that I can take a look?

Page is live here: http://www.nba.com/heat/test-gif-page

We use Drupal as our CMS, if that matters.

The script seems to be working OK, but the GIF version of each image doesn’t exist, which is why you’re getting the broken image icon. For example, the file OdenDunkBackGo.jpg is displayed, and rolling over the image tries to load OdenDunkBackGo.gif, but the server is returning 404 not found.

You sir, are the best. There was an error with our FTP that was causing filename errors with .gif’s. Easy fix, and it’s working great now.

Thank you so much. That’s going to save me a great deal of time this year.

Everything was great last night, but when attempting to publish a new page using the exact same code everything stopped working.

the page I’m trying to publish is this: http://www.nba.com/heat/news_recap/return-rose-and-heats-defense

This might be an issue with our servers or CMS, since it doesn’t make sense that even my test page from before would stop working:

http://www.nba.com/heat/test-gif-page

But if you feel like taking a look or have an idea for why the script would stop loading, let me know.

Thanks.

The problem seems to be the sheer size of the animated gifs. At first, it looks like nothings is happening when you hover over the images. But, I opened up the Network tab in Chrome’s developer tools and when I hovered over one of the images I could see the image being loaded, but it took many seconds to load the whole image and the image doesn’t swap until it has finished.

Yes, that’s the issue now so it’s manageable. Something else was going for most of yesterday, but we had to get some tech developers on it and hopefully it’s resolved now.