Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
How can I append a date or time to an image and prevent it from caching using jQuery or JavaScript?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

$('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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!