dubbs
dubbs

Reputation: 1199

jQuery append img src

How can I add "_small.jpg" to the img src of a bunch of images I have in a div called "banners"?

I have a jQuery script listening for window resizes - and when below 400px I want to change the img src of the images to include "_small.jpg" at the end to call in the small image source. So...

<img src="example.jpg" />

when viewed at screen sizes below 480px would then become

<img src="example_small.jpg" />

How would I do this?

P.S. I'd like the script to loop through all the images in the "banners" div to update them btw :)

Upvotes: 0

Views: 8407

Answers (3)

drew_w
drew_w

Reputation: 10430

You might try:

// define this somewhere in your code (credit: https://stackoverflow.com/questions/280634/endswith-in-javascript)
function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

if ($(window).width() < 480) {
  $("div.banners img").each(function() {
    if (!endsWith($(this).attr('src'), '_small.jpg')) {
      // if you have more than "jpg" files you will want to replace those as well
      $(this).attr('src', $(this).attr('src').replace(/\.jpg/, '') + '_small.jpg');
    }
  });
}

I believe that should do it!

Edit - Added an extension remove based on a comment. For more information on replacing extensions see this stack.

Edit 2 - Added a check for "endswith" in case the function is called on items that already have the small extension added!.

Upvotes: 0

hsz
hsz

Reputation: 152206

You can try with:

var src = $('img').attr('src'),
    ext = src.substr( src.lastIndexOf('.') );

src = src.replace(ext, '_small' + ext, src);

$('img').attr('src', src);

Or with regex:

var src = $('img').attr('src'),
    src = src.replace(/(\..*)$/, '_small$1', src);

$('img').attr('src', src);

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

You can do:

$("div.banners img").each(function() {
    $(this).attr("src", function() {
        var src = this.src.split(".")[0];
        return src + "_small.jpg";
    });
});

(The above assumes image names have no "." in them and all have a type of JPEG)

Upvotes: 1

Related Questions