Jump to content

Trying to clear image from div


EchoFool

Recommended Posts

Hey

 

I have a function which i call every 2 seconds with a timeinterval but the issue i have is i can't seem to unset the image before re-assigning it the next time round, so currently it duplicates the image instead of only showing one of them.

 

I tried the below function to clear it but it doesn't seem to like it.

 

 

var area = 1;
function fillarea(area){
var randomnumber=Math.floor(Math.random()*10);
var randomnumber2=Math.floor(Math.random()*10);
var newDiv = area+":"+randomnumber+":"+randomnumber2;
if(last != undefined){ document.getElementById(last).innerHTML=""; }  //its unset first time round so skip to avoid error
document.getElementById(newDiv).innerHTML="<img src='tile.PNG'/>";
var last = newDiv;
}

setInterval( "fillarea()", 2000);

 

 

Any idea where im going wrong ?

Link to comment
https://forums.phpfreaks.com/topic/222235-trying-to-clear-image-from-div/
Share on other sites

function fillarea(area){

setInterval( "fillarea()", 2000);

Either you're not passing the area when you should, or you shouldn't be expecting it since it isn't being passed.

 

If you don't name it as an argument then your function can use the outer area.

Okay i added this :

 

setInterval( "fillarea(area)", 2000); which now shows the image - thanks :)

 

But it doesn't clear the image that it generated prior to generating it again in a new area. It just makes lots of the image at random places instead of clearing the one before generating the next. So that only one image will show at a time.

 

Any ideas as to why this is ?

Your variable "last" does not maintain state between function calls. It will always be undefined.

The solution is to use javascript closures. Here's a working example http://gonavygolf.com/test3.php

 

(function fillarea() {
    
    var randomnumber=Math.floor(Math.random()*3);
    var randomnumber2=Math.floor(Math.random()*3);
    var newDiv = area+":"+randomnumber+":"+randomnumber2;
    var area = 1;
    var last;
    
    var setDiv = function () {
       
       randomnumber=Math.floor(Math.random()*3);
       randomnumber2=Math.floor(Math.random()*3);
       newDiv = area+":"+randomnumber+":"+randomnumber2; 
       
       if(last != undefined){ document.getElementById(last).innerHTML=""; }  //its unset first time round so skip to avoid error
            document.getElementById(newDiv).innerHTML="<img src='sanDiego.jpg'/>";
        last = newDiv;
    }
    
    setInterval(setDiv, 2000);
    
})();

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.