JQuery attr function to replace image src not working in browsers except Chrome

Hi all,

As per title, I believe there are a lot people who face this problem when want to dynamically update an image using JQuery.
Once there is a requirement for this, the first thing come out in mind is the .attr() function provided by JQuery. The code roughly will be like this:

$('#<image element id>').attr('src',<new image source>);

Logically this should be done the job. However, after a test in several browsers, one will find out that this only working in Chrome. Internet Explorer, Firefox and Safari do not perform as expected.
Why will this happen? It is due to cache issue.
The solution for this issue is very simple. It is just needed to append a timestamp behind the new image source to trick the browser that the image is a new one for each time the function is triggered.
It is as below:

$('#<image element id>').attr('src', <new image source>?' + new Date().getTime());
* the part highlighted in yellow is the additional part to add into the code.

Refresh your browser and try dynamically change the image again. It should be working this time. :)

Happy coding!!!

Comments

  1. this is not working in chome
    var navbar_logo = $('.navbar-logo img');
    src = navbar_logo.data('logo-dark')+'?'+new Date().getTime();
    navbar_logo.attr('src', src);

    ReplyDelete
  2. its not working
    $('#blah').attr('src', e.target.result+'?' + new Date().getTime());
    }

    ReplyDelete

Post a Comment

Popular posts from this blog

Django Form: MultipleChoiceField and How To Have Choices From Model Example

DJango Queryset comparing date time

Jquery Validation fix for date format dd/mm/yyyy in Chrome and Safari