user1294097
user1294097

Reputation: 153

dynamic <img> refresh with javascript

I'm trying to get an user input image to refresh say every two seconds. The javascript gets user input for an URL and the javscript adds it to the page. Then the images loaded need to refresh every 2 seconds but i can't get it to refresh properly without refreshing the whole page or reloading from the cache:

function getImg(){

var url=document.getElementById('txt').value;
var div=document.createElement('div');
div.className="imageWrapper";
var img=document.createElement('img');
img.src=url;
div.appendChild(img);
document.getElementById('images').appendChild(div);
return false;
}

setInterval(function(){
    $('img').each(function(){
       var time = (new Date()).getTime();
       $(this).attr("src", $(this).attr("src") + time );
    });
}, 2000);

any ideas?

Upvotes: 0

Views: 2567

Answers (3)

Eduardo Chongkan
Eduardo Chongkan

Reputation: 800

Put the image in a container as:

<div id="container"><img src=""../> </div>

then simply update the content of the container as:

$('#container').html('<img src="newSource"../>');

Upvotes: 0

mrtsherman
mrtsherman

Reputation: 39902

Your premise seems good, not sure why it isn't working. Why mixing and matching jQuery with non-jquery? This is a modification of your code, but it is a working example. You should be able to adapt it for your purpose.

http://jsfiddle.net/zr692/1/

You can create elements via jQuery easily. See the modified getImg function I created. Ia also switched from attr to prop which is the recommended means of accessing the src attribute in jQuery 1.7+.

function getImg() {
    var url = 'http://placehold.it/300x300/123456';
    var $div = $('<div />');
    var $img = $('<img />', { src: url });
    $div.append($img);
    $('body').append($div);
}

getImg();

var interval = setInterval(function() {
    $('img').each(function() {
        var time = (new Date()).getTime();
        var oldurl = $(this).prop('src');
        var newurl = oldurl.substring(0, oldurl.lastIndexOf('/') + 1) + time.toString().substr(7, 6);
        $('#output').html(newurl);
        $(this).prop('src', newurl);
    });
}, 2000);

Upvotes: 0

pylover
pylover

Reputation: 8075

When you need to force reload the resource, you have to add a dymmy queryString at the end of your url:

<img id="img1" src="myimg.png?dummy=23423423423">

Javascript:

$('#img1').attr('src','myimg.png?dummy=23423423423');

and change the dummy value for each refresh

Upvotes: 2

Related Questions