tags:

views:

38664

answers:

3

I have this code to give me a rollover on submit buttons, and I'm trying to make it more generic:

$('.rollover').hover(
            function(){ // Change the input image's source when we "roll on"
                srcPath = $(this).attr("src");
                            srcPathOver = ???????
       /*need to manipulate srcPath to change from
       img/content/go-button.gif
       into 
       img/content/go-button-over.gif
       */
       $(this).attr({ src : srcPathOver});
            },
            function(){ // Change the input image's source back to the default on "roll off"
                $(this).attr({ src : srcPath});
      }
     );

Two things really,

I want to learn how manipulate the srcPath variable to append the text '-over' onto the gif filename, to give a new image for the rollover. Can anyone suggest a way to do this?

Also, can someone tell me if this code could be refined at all? I'm a bit new to jQuery and wondered if the syntax could be improved upon.

Many thanks.

+2  A: 

You should be able to use a regex replace to modify your source path. Like this:

srcPathOver = srcPath.replace(/([^.]*)\.(.*)/, "$1-over.$2");

More on JavaScript regexes here

As far as how you're doing it, I'd make sure that you define your srcPath variable like this

var srcPath;
$('.rollover').hover(...

The code you have above makes it look like srcPath is a global variable, which is not what you want.

Matt Ephraim
+4  A: 

To manipulate the file name and append "-over" you simply have to do some javscript string manipulation, like this:

function appendOver(srcPath){
    var index = s.indexOf('.');

    var before = s.substr(0, index);
    var after = s.substr(index);

    return before + "-over" + after;
}

This should return the original filename (in all possible formats) and add the '-over' string just before the extension dot.

Lck
+7  A: 
$('.rollover').hover(
            function(){ // Change the input image's source when we "roll on"
                var t = $(this);
                t.attr('src',t.attr('src').replace(/([^.]*)\.(.*)/, "$1-over.$2"));
            },
            function(){ 
                var t= $(this);
                t.attr('src',t.attr('src').replace('-over',''));
            }
     );
John C
Don't forget var, as in var t = ...
Tom Viner
edit: thx... added the var
John C