1

I have an auto-generated form that also handily displays thumbnails. I want to add a button beside the image that will refresh it if it is updated. I want to take cached images into account.

I add a button easily enough:

// add a refresh button to image previews
$('a[href*="/thumbs/"]').after('<div class="refresh-image"><button class="refresh-image-button">Refresh</button></div>');

And since I'm okay if the refresh button refreshes all of the stale images I try to append a query string to the image src (deleting an old query string if it exists):

// attach refresher to button
$(".refresh-image-button").click(function() {
    $('img[src*="/thumbs/"]').attr("src", $(this).attr("src").split('?',1)+'?'+Date.now());
});

However, I can't really do this because here $(this) doesn't refer to the matched image, and I can't do a split operation within this jquery match anyway.

How do I do it?

As a bonus if anyone has a ref to decent auto refresh image code, that would be helpful.

This builds on a simpler SO inquiry here.

Community
  • 1
  • 1
Wes Modes
  • 2,024
  • 2
  • 22
  • 40

3 Answers3

1

Iterate through the collection:

$(".refresh-image-button").click(function() {
    $('img[src*="/thumbs/"]').each(function() {
        $(this).attr("src", $(this).attr("src").split('?',1)+'?'+Date.now());
    });
});

http://jsfiddle.net/g68gxu93/1/

Miguel Mota
  • 20,135
  • 5
  • 45
  • 64
0

You could generate a variable with the new trailing parameter separately like :

$(".refresh-image-button").click(function() {
    var newAttr = $('img[src*="/thumbs/"]').attr("src").split("?")[0] + "?ver=" + new Date().getTime();
    $('img[src*="/thumbs/"]').attr("src", newAttr);
});

see JSFIDDLE

JFK
  • 40,963
  • 31
  • 133
  • 306
0

I ended up doing something almost precisely like @Moogs answer.

addRefreshButtons();

// NICEITIES

function addRefreshButtons() {
  // add a refresh button to image previews
  $("div.refresh-image").remove();
  $('a[href*="/thumbs/"]').after('<div class="refresh-image"><button class="refresh-image-button">Refresh</button></div>');
  // attach refresher to button
  $(".refresh-image-button").click(function() {
      refreshThumbnails();
  });
}

function refreshThumbnails() {
    $('img[src*="/thumbs/"]').each(function() {
        var src = $(this).attr('src');
        var newSrc = src.split('?',1)+'?'+Date.now()
        $(this).attr('src', newSrc);
    });
}
Wes Modes
  • 2,024
  • 2
  • 22
  • 40