views:

716

answers:

1

Hey guys,

I am using an image switch function in Jquery for a site I am building. There are a ton of projects so I am heavily compressing a lot of these images. Some of them however dont look nice as .gifs and it really only makes sense to make a .jpg.

My problem is that this code only swaps one image, to another image of a different name but similar prefix. Is there a way to swap just the name of the file, so that if I have a .gif, or .jpg, it wouldn't matter as it would just be swapping the name from _static to _rollover?

Here is the code I am using:

//Image Switch
$(document).ready(function(){
    $(".projectThumb img").hover(
            function(){
                    var iconName = $(this).attr("src");
                    var origin = iconName.split("_static.")[0];
                    $(this).attr({src: "" + origin + "_rollover.gif"});
            }, 
            function(){
                    var iconName = $(this).attr("src");
                    var origin = iconName.split("_rollover.")[0];
                    $(this).attr({src: "" + origin + "_static.gif"});
            });
});

and the HTML for the image switch

<div class="projectThumb">
    <img src="/img/mr_button_static.gif" class="button" name="mr">
    <p class="title">Title &ndash; Poster</p>
</div>

The image to be switched is named /img/mr_button_rollover.jpg

Thanks!

+2  A: 

Just use string replacement to switch between static and rollover in the image name.

//Image Switch
$(document).ready(function(){
    $(".projectThumb img").hover(
            function(){
                    var iconName = $(this).attr("src");
                    var rollover = iconName.replace( /static/, 'rollover' );
                    $(this).attr({ src: rollover });
            }, 
            function(){
                    var iconName = $(this).attr("src");
                    var static = iconName.replace( /rollover/, 'static' );
                    $(this).attr({ src: static });
            });
});

If there is a possibility that you could static/rollover in the image prefix, simply include the underscore in the search and replace strings and match/replace the dot before the file extension.

tvanfosson
This seems pretty simple enough. It works fine for all the .gifs, but the .jpg ones do not switch over…Here is an example…http://samuelfarfsing.com/columns.phpIf you look at the "JPEG SWITCH" one, that is the one that will not switch over…
Anthony
Both images the rollover and the static image need to be either GIF or JPEG for this to work. If you want to be able to switch out a GIF for a JPEG, then you'll need some extra data in the title to be able to tell when to change the extension, too. If you don't care about using standard HTML you could also use a custom attribute to tell what extension the rollover image should have. I would go the simple direction and have them both be the same type.
tvanfosson