1

I have the following script provided by user Vincent - he really helped me out but I just haven't got the understanding to finish it on my own...

It adds a '_' prefix to an image file onclick (swapping '1.gif', say, for '_1.gif').

To complete I need some way of swapping back onclick (removing that '_' prefix if it is present).

<script type="text/javascript" src="jquery.js"></script>      
<script type="text/javascript">
var prefix = "_";
function showNextPic(imgelement)
{
    var src = imgelement.attr('src');
    if(src.indexOf(prefix) == -1) {
         src = prefix + src;
    }
    imgelement.attr('src', src);
}
</script>

with

onClick="showNextPic($(this))

with each image.

Can anyone help me remove that prefix if it's present?

Thanks very much for reading!

Suresure
  • 143
  • 11

1 Answers1

1
function showNextPic(imgelement)
{
    var src = imgelement.attr('src');
    if(src.indexOf(prefix) == -1) {
         src = prefix + src;
    }
    else if(src.indexOf(prefix) == 0) {
             src = src.substring(1);
    }
    imgelement.attr('src', src);
}
Raab
  • 34,778
  • 4
  • 50
  • 65
  • Hey, thanks for the speed! I'm really sorry, I'm a total beginner. You're right with it being just the first character - but nothing's happening on that second click. Do I need to call this new function into action somehow? Groan, sorry for my ignorance... – Suresure Jul 07 '12 at 19:38
  • Aw magic! That's so clean! Thanks. The original code I'd mashed together was really nasty. Uh... any chance you could show me how to preload all images with that prefix? Sorry, I don't want to push it... – Suresure Jul 07 '12 at 19:45
  • nope, question already exists... http://stackoverflow.com/questions/476679/preloading-images-with-jquery – cprogcr Jul 07 '12 at 19:48
  • Haha! Thanks Rab - you did a really nice job. – Suresure Jul 07 '12 at 19:49
  • Cheers cprogcr - I hadn't searched, I'll try that one out! – Suresure Jul 07 '12 at 19:50