2

For the last few hours I have scoured for a way to do this and have com up with nothing. I am trying to figure out a way to change only a sub string within an attribute. An example of what I would like to do is change

<a href="media/gallery/jtnp/JT.JPG" rel="shadowbox[JTNP]" title="Joshua tree" class="shaddowimages"><img id="JTth" src="media/gallery/jtnp/b_thum/JTthumb.JPG" alt="A small Joshua tree"></a>

to

<a href="media/gallery/jtnp/JT.JPG" rel="shadowbox[JTNP]" title="Joshua tree" class="shaddowimages"><img id="JTth" src="media/gallery/jtnp/s_thum/JTthumb.JPG" alt="A small Joshua tree"></a>

Here is what I have so far, however nothing happens when I attempt to press the button #changethumb.

$(document).ready(function() {

    var count = 0;

    $('#changethumb').click(function() {

        if (count === 0) {
            $('#shaddowimages img').each(function() {
                $(this).attr('src', $(this).attr('src').replace('b_', 's_'));
            });
            count = 1;
        } else {
            $('#shaddowimages img').each(function() {
            $(this).attr('src', $(this).attr('src').replace('s_', 'b_'));    
            });
        count = 0;
        }
    })
});

I could go through and replace each src manually, but having 20+ images, I would like a way to automate this if I could. Any help?

Falahan
  • 23
  • 3

2 Answers2

2

Use .attr( attributeName, function(index, attr) )

$('#shaddowimages img').attr('src', function (i, old) {
    return old.replace('b_', 's_');
});

or Better use .prop( propertyName, function(index, oldPropertyValue) )

$('#shaddowimages img').prop('src', function (i, old) {
    return old.replace('b_', 's_');
});

Read .prop() vs .attr()

Community
  • 1
  • 1
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
  • 1
    This reply made the most sense to me, Thank you for providing links to other reading, that really helps explain this to me. – Falahan Nov 07 '13 at 15:50
0

Can run all your logic within attr so you don't have to duplicate code in your 'if

 $('#changethumb').click(function() {
    $('#shaddowimages img').attr('src', function (i, src) {
         var newSrc= count==1 ? src.replace('b_', 's_') : src.replace('s_', 'b_');
         count=  count == 1 ? 10 : 1;
          return  newSrc;
    });
 });

Seems strange that count is only 1 or 10. Copied your code but it doesn't make sense

charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • I changed the 1 and 10. It made sense to my overtired head, but 0 and 1 are much cleaner to read. – Falahan Nov 07 '13 at 15:51