Search code examples
javascriptjqueryrollover

Creating button rollovers with jQuery


I'm trying to make a function that I can use globally to create rollover states for images. Basically, I want to be able to add a class to an image, and then when you rollover it, jquery will use the same image name, and same extension, but add "-over" to the file name. (I'll have an image with the rollover state named the same as the non rolled over state except with the -over on it. I came up with this, but it's not working. Am I doing something wrong or does anyone know of a better way to do it?

$('.btn').hover(function(){
    $(this).attr("src").split(".jpg").join("Over.jpg"));
});

image:

<img src="/static/images/overlay-close-button.jpg" alt="Close" title="Close" id="our-staff-overlay-close" class="btn"/>

Thanks!

EDIT: Is there any way to make it non specific to the file time, where it can figure out any file type rather than just jpgs?

I'm using:

$('.btn').hover(function(){
    this.src = this.src.split(".jpg").join("Over.jpg");
}, function() {
    this.src = this.src.split("Over.jpg").join(".jpg");
 });

and it's working great

EDIT 2: Can I also add an active state (when the button is being clicked)?


Solution

  • The splitting and joining should work as intended, you just need to set that back to the src attribute of the img:

    $('.btn').hover(function() {
        var src = $(this).attr("src");
        src = src.split('.jpg').join('-over.jpg');
        $(this).attr("src", src);
    });
    

    Also, if you want it to work with any extension, you could use a regular expression like this:

    $('.btn').hover(function() {
        var src = $(this).attr("src");
        src = src.replace(/(.*)\.(png|gif|jpg|jpeg)$/, "$1-over.$2");
        $(this).attr("src", src);
    });
    

    The regular expression matches anything that ends with a period followed by one of png, gif, jpg, or jpeg, and replaces it with the first part (the path + filename), the string "-over", a period, and the original extension.

    You can replace it back to the original state by removing the -over from the source:

    $('.btn').hover(function() {
        var src = $(this).attr("src");
        src = src.replace(/(.*)\.(png|gif|jpg|jpeg)$/, "$1-over.$2");
        $(this).attr("src", src);
    }, function() {
        var src = $(this).attr("src");
        src = src.replace(/(.*)-over\.(png|gif|jpg|jpeg)$/, "$1.$2");
        $(this).attr("src", src);
    });
    

    The jQuery().hover event accepts two functions, the first one is called when you start the hover, the second one is called when you exit the hover.