1

I am trying to change the ending of our image src's in order to render images smaller on mobile. We use Adobe Scene 7, so I can set presets for a full size image, and then a mobile image and then I just need code to make the url change. I found this question on here and am trying to apply it to my code. My problem is that I have no idea how to write a regular expression for this, the dollar signs are throwing me off.

$('img').each(function () {
    var src = $(this).attr('src');
    $(this).attr('src', src.replace($fullbanner$, '$mobilebanner$');
}); 

So to make it simple, could someone help me write a regular expression that would fill in the "src.replace( , );" section? The initial value of the url would be domain/company/banners/homepage/img_name?$fullbanner$ and then we just need it to change to domain/company/banners/homepage/img_name?$mobilebanner$.

Also, if it's as easy as just saying:

src.replace('$fullbanner$', '$mobilebanner');

then just say so. I really appreciate any help that is offered.

Community
  • 1
  • 1

1 Answers1

2

You can use attr(function) which will loop over each instance:

$('img').attr('src', function(index, existingSrc){
    return existingSrc.replace('$fullbanner$', '$mobilebanner');
});

Note that this isn't a very effective strategy as it won't prevent the browser making the initial requests for the full size images since any images that exist in initial page load will already have requests made before your script runs

charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • What could i do to prevent the browser making that initial call for full size images? @charlietfl – idontwantnoscrubs Oct 05 '15 at 17:35
  • set small by default and upsize to large on larger devices or don't set the `src` in html and set it with script from a data attribute using same approach as this answer but from alternate data source – charlietfl Oct 05 '15 at 17:37
  • This is great advice thank you, I will give it a shot using your method and if it works for me i'll come back and hit the checkmark. – idontwantnoscrubs Oct 05 '15 at 17:46
  • @charlieftl actually, I did have one more question. If I wanted to apply this to multiple different sets of images, such as product image thumbnails, product images, product videos etc... Would I just duplicate this code and change out the value inside the existingSrc.replace( ); for each one or is there a way to minimize this code and include all of the different variations? – idontwantnoscrubs Oct 05 '15 at 17:54