Search code examples
javascriptjqueryimagerandomfadeout

Randomly remove image from game space without using class in JavaScript/jQuery


I am trying to have the Moles (little cubes in https://jsfiddle.net/JennyF/s4rteuks/13/) randomly disappear form the #gamespace if they are not clicked on. They randomly appear between 0 - 2 seconds. The game is working on Firefox without this question addressed while including my attempt, but it is not working in JSFiddle.

      function addMole(){
        xPos=randPosX();
        yPos=randPosY();
        $("#gamespace").append('<img src="img/mole.png" style="top:'+xPos+'px; left:'+yPos+'px;" />');
        var r=Math.floor(Math.random()*(2000));
        t=setTimeout("addMole();", r);
        var count=0;
        setTimeout("remove()", 1000);
        function remove(){
            $("#gamespace").append("<img id='img"+count+"'></img>");
            count++;
            setTimeout("remove()", 1000);
        };
    };//end mole

My instructor told us not to use a class and gave us this example. Obviously, I want to fadeOut instead of add anything. And I don't have any <p> tags. I just don't know what to put in their place. Or if I totally messed it up.

var count=0;
setTimeout("add()", 1000);
function add(){
$("div#div1").append("<p id='p"+count+"'></p>");
count++;
  setTimeout("add()", 1000);}

Solution

  • Well, here is the corrected code and my jsfiddle https://jsfiddle.net/JennyF/s4rteuks/14/, which doesn't work, it works in my program, though. I don't know what I'm doing wrong in jsfiddle. I copied everything exactly and attached the right jQuery library.

        function addMole(){
            if (time_left >0){
                xPos=randPosX();
                yPos=randPosY();
                $("#gamespace").append('<img id='+count+' src="img/mole.png" style="top:'+xPos+'px; left:'+yPos+'px;" />');
                var f='#'+count;
                count++;                
                $("#gamespace").find(f).delay(1500).fadeOut();
                var r=Math.floor(Math.random()*(2000));
                t=setTimeout("addMole();", r);
                }else{
                    clearTimeout(t);
                    $("#gamespace").off("click", "img");
                };//end if
        };//end mole