I created the following javascript code that appends a new date and time on click so that the browser does not pick up the image from the cache and loads it everytime. My code is:
$(#button).click(function(e) {
e.preventDefault()
$('.Myimage').attr('src',$('this').src + 'Testimage.png' + '?' + (new Date().getTime()));
});
This almost works fine but I'm getting an undefined message at the beginning of my image string.
<img src="undefinedTestimage.png?1628621212728" class="Myimage">
I'm not sure why. I figure that its some sort of typo. I'm also open to improving the code. Suggestions?
$('this') is selecting a <this> element.
If you change it to $(this) it still won't be correct, because this is the button, not the image. Also, in jQuery you use .attr('src') to get the src attribute, not .src.
If you want to get the image's src, you need to loop over all the .Myimage elements. You can do that by giving a function argument to the .attr() method. This receives the old attribute as an argument, and returns the new value.
You don't need to concatenate Testimage.png, since that should already be in the src.
$('#button').click(function(e) {
e.preventDefault();
$('.Myimage').attr('src', (i, src) =>
src + '?' + (new Date().getTime()));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="foo.png" class="Myimage">
<img src="bar.png" class="Myimage">
<br>
<button id="button">Click</button>