<html>
<style>
	#playingArea
	{
		position: absolute;
		top: 1;
		left: 1;
		border: 5px solid black;
		width: 750;
		height: 720;
		z-index: 2;
	}
	#basket
	{
		position: absolute;
		top: 650;
		left: 228;
		width: 64;
		height: 16;
	}

</style>

<script type="text/javascript" language="Javascript">
var basket;
var basketLeft = 228;

function keyListener(e)
{
	e = window.event;
	if (e.keyCode==37 && basketLeft > 0)
	{
		basketLeft -= 8;
		basket.style.left = basketLeft + 'px' ;
	}
	if (e.keyCode==39 && basketLeft < 436)
	{
		basketLeft += 8;
		basket.style.left = basketLeft + 'px' ;
	}
}

function init()
{
basket=document.getElementById('basket');
document.onkeydown=keyListener;
fall();
}

grphcs=new Array(5)
Image0=new Image();
Image0.src=grphcs[0]="1.gif";
Image1=new Image();
Image1.src=grphcs[1]="2.gif";
Image2=new Image();
Image2.src=grphcs[2]="3.gif";
Image3=new Image();
Image3.src=grphcs[3]="4.gif";
Image4=new Image();
Image4.src=grphcs[4]="5.gif";

Amount=5;
Ypos=new Array();
Xpos=new Array();
Speed=new Array();
Step=new Array();
Cstep=new Array();
var Stop=false;

	for(i=0;i<Amount;i++)
		{
			var P=Math.floor(Math.random()*grphcs.length);
			rndPic=grphcs[P];
			document.write('<img id="si'+i+'" src="'+rndPic+'"style="position:absolute;top:0px;left:0px">');	
		}
		
WinHeight=document.body.clientHeight;
WinWidth=document.body.clientWidth;

for(i=0;1<Amount;i++)
	{
		Ypos[i]=Math.round(Math.random()*WinHeight);
		Xpos[i]=Math.round(Math.random()*WinWidth);
		Speed[i]=Math.random()*5+3;
		Cstep[i]=0;
		Step[i]=Math.random()*0.1+0.05;
	}

function fall()
{
	if(Stop)
	{clear();
		return;
	}
	
	var WinHeight=document.body.clientHeight-100;
	var WinWidth=document.body.clientWidth-500;
	
	for(i=0;i<Amount;i++)
		{
			sy=Speed[i]*Math.sin(90*Math.PI/180);
			sx=Speed[i]*Math.cos(Cstep[i]);
			Ypos[i]+=sy;
			Xpos[i]+=sx;
			if(Ypos[i]>WinHeight)
			{
				Ypos[i]=60;
				Xpos[i]=Math.round(Math.random()*WinWidth);
				Speed[i]=Math.random()*5+3;
			}
			
			else
			{
				document.getElementById("si"+i).style.left=Math.min(WinWidth,Xpos[i])-200;
				document.getElementById("si"+i).style.top=Ypos[i];
			}
			Cstep[i]+=Step[i];
		}
		
	setTimeout('fall()',20);
	}
	setTimeout("Stop=true",30000);
	
	function clear()
	{
		for(i=0;i<Amount;i++)
		document.getElementById("si"+i).style.display='none';
	}
	
</script>

<body onload="init()";>
		
		<div id= "basket">
			<img src= "basket.jpg">
		</div>
		
		<div id= "playingArea">
		</div>



</body>

</html>

i need to have the score added here every time the basket catches fruits..how? pls help! thank you! :(

The code line below is changed because it wouldn't work on FF with original code.

// need to change to this because previous version doesn't work with FF
  if (!e || (typeof(e)=="undefined")) { e = window.event; }

The code block below, yours was '1', but it is supposed to be 'i'

for(i=0;i<Amount;i++) { // i, not 1<Amount
  Ypos[i]=Math.round(Math.random()*WinHeight);
  Xpos[i]=Math.round(Math.random()*WinWidth);
  Speed[i]=Math.random()*5+3;
  Cstep[i]=0;
  Step[i]=Math.random()*0.1+0.05;
}

Now, when you need to add score, you need to add code that detect whether the falling item is going into the basket. The code portion should be inside your keyListener. It could be below your style assignment.

function keyListener(e) {
  if (!e || (typeof(e)=="undefined")) { e = window.event; }
  if (e.keyCode==37 && basketLeft > 0) {
    basketLeft -= 8;
    basket.style.left = basketLeft + 'px' ;
    // Here, add the code to detect whether the falling item is in the basket
    // 1.check if the location of the item is in the bucket
    //   1.1.check if Ypos of each of all items is at the bottom most that it can go
    //       (depends on how you determine bottom most -- could be at the top of bucket
    //       or has to be completely inside the bucket).
    //   1.2 check if Xpos of each of those in the 1.1 is within the range of basket.
    // 2.if it is in, add the score, otherwise, do nothing (no else statement).
  }
  if (e.keyCode==39 && basketLeft < 436) {
    basketLeft += 8;
    basket.style.left = basketLeft + 'px' ;
    // Here, add the code to detect whether the falling item is in the basket
    // 1.check if the location of the item is in the bucket
    //   1.1.check if Ypos of each of all items is at the bottom most that it can go
    //       (depends on how you determine bottom most -- could be at the top of bucket
    //       or has to be completely inside the bucket).
    //   1.2 check if Xpos of each of those in the 1.1 is within the range of basket.
    // 2.if it is in, add the score, otherwise, do nothing (no else statement).
  }
}

I can't give an example code for you because I do not know how big the image for each of those items + basket are. Also, I have a feeling that these codes are from your professor and the professor wants you to modify it as a practice or assignment. I already gave you the location of code you need to add in and what you need to check for. The portion of the code can be a function, so you only call a function right after the style change as well as you need to modify code in only one place -- the function definition. Hope this should be enough for you to do it yourself.

Hey, Taywin! I tried to add collision detection to the code posted by the thread's author but I'm having trouble trying to figure out how to pull in the x and y coordinates of the different eggs that are falling randomly. Would you be able to tell me what I'm doing wrong? Thank you!

    `function keyListener(e) {
        document.getElementById("si"+i).style.top=eggsTop;
        document.getElementById("si"+i).style.left=eggsLeft;
        if (!e || (typeof(e)=="undefined")) { e = window.event; }
        if (e.keyCode==37 && basketLeft > 0) {
            basketLeft -= 8;
            basket.style.left = basketLeft + 'px' ;
        if (basket.style.left < eggsLeft + 65 &&
            basket.style.left + basket.style.width > eggsLeft &&
            basket.style.top < eggsTop + 84 &&
            basket.style.height + basket.style.top > eggsTop) {
                console.log("collision");
            }
        }
        if (e.keyCode==39 && basketLeft < 436){
            basketLeft += 8;
            basket.style.left = basketLeft + 'px' ;
        }
    }`

Hmm... This is an old post... Also, your function is using global values which is no where to be seen before in your script (i.e. i, eggsTop, eggsLeft, etc.). I think you need to try to understand the script first. Then you need to explain to me how you think this should work...

Also, you are assigning a "string" value to basket.style.left but then attempt to compare with integer (65, etc.). That will not work because it will never be comparable...

Thank you so much for the quick response! For the most part I'm able to understand the code but I'm having trouble trying to harness what is being fed into the style tag of the individual falling objects. That's why I attempted to use the integer to be able to get around not being able to access the width and the height of the ("si"+1) ids. Does that make sense? :S

OK, thanks.

The purpose of i in the original post is to iterate through all displayed eggs on the screen. Each egg is displayed in a HTML element with style properties. The variable xPos and yPos save all position x & y of corresponding egg index. Each time the egg moves, a new position is computed first before update the egg display style. These variables are global (can be seen/accessed anywhere in the script). The i, however, is not supposed to be a global. It is used to point to the corresponding egg index. That's why the for loop is being used in the script.

Now, in each collision detection part, you must iterate through each egg and check its x & y position from the array. You should be able to access those variables because they are global. Hope this help.

Does this mean I have to write an if statement for each egg id (i.e. si0, si1, si2, ect.) checking its coordinates against the basket's or is there a more concise way to do it?

You need to write a for loop statement to go through each of the egg position. The grphcs array variable stores the egg display. The index of each element in the array corresponds to the index of xPos and yPos array. In other word, grphcs[0] is the the egg0 and has x position stored in xPos[0] and y position stored in yPos[0]. Hope this help.

Is this right? :S

function keyListener(e) {
    if (!e || (typeof(e)=="undefined")) { e = window.event; }
    if (e.keyCode==37 && basketLeft > 0) {
        basketLeft -= 8;
        basket.style.left = basketLeft + 'px'   
    for(i=0;i<Amount;i++) {
        if (basket.style.left < grphcs[i].x + grphcs[i].width &&
            basket.style.left + basket.style.width > grphcs[i].x &&
            basket.style.top < grphcs[i].y + grphcs[i].height &&
            basket.style.height + basket.style.top > grphcs[i].y) {
                    console.log("collision");
            }
        }
    }

    if (e.keyCode==39 && basketLeft < 436){
        basketLeft += 8;
        basket.style.left = basketLeft + 'px' ;
        }
    }

Sorry for all the back and fourth. I really appreciate your patience.

It looks much better :) However, the Amount should be the length of grphcs variable instead of an arbitrary global variable like that. The reason is that you are directly dealing with grphcs variable, you should keep the loop to go within the bound of the variable.

Now, the style value could come in as String (depending on browser). What you need to do when you want to compare something like that is to force them to be number (integer) by using parseInt() function (i.e. parseInt(basket.style.left, 10) which force the value of left to be an integer base 10). This should also apply to any style value you are directly retrieving from an element.

Also, when you are iterating an array, you must understand what element/data type inside the array. In this case, it should be an image tag. The image tag does not have x property. You could force style value into the tag as inline style. However, the original post use xPos and yPos to hold the left & top value of the image. Therefore, instead of using graphcs[i].x, it should be xPos[i]. The similar applies to yPos variable.

Hope this help.

Hey, Taywin. I had a chance to revise my code and this is how did it.

function keyListener(e) {
    if (!e || (typeof(e)=="undefined")) { e = window.event; }
    if (e.keyCode==37 && basketLeft > 0) {
        basketLeft -= 8;
        basket.style.left = basketLeft + 'px' 
        for(i=0;i<grphcs.length;i++) {
            if(parseInt(basket.style.left, 228) > Xpos[i] + `Inline Code Example Here`parseInt("si"+i.style.width, 65) || parseInt(basket.style.left, 228) + parseInt(basket.style.width, 100) <
            Xpos[i] || parseInt(basket.style.top, 650) > Ypos[i] + parseInt("si"+i.style.height, 84) || parseInt(basket.style.top, 650) + parseInt(basket.style.height,
            150) < Ypos[i]) {
                console.log("collision");
        }
    }
}   
    if (e.keyCode==39 && basketLeft < 436){
        basketLeft += 8;
        basket.style.left = basketLeft + 'px' ;
    }
}

However, every time I move the basket left and right I'm getting an error in the console stating that width is not defined. I suspect it might because of the way I'm trying to obtain the dimensions of the individual eggs (i.e. parseInt("si"+i.style.width, 65). Am I correct? How can I resolve this? Thanks!

Oh? Something is not wright in line 7. :P Did you copy & paste? It won't work because `Inline Code Example Here ` will cause syntax error.

Also, parseInt(String, base_number) should not have 228 as a base value. In number, we are using base 2, 8, 10, and 16!

Sorry about that! The 'inline code example' was not meant to be included. What do the base values 2, 8, 10 and 16 represent exactly? How do I know which to assign to basket and which to assign to"si"+i? Is it arbitrary? Also, I noticed you didn't mention anything about the way I had written parseInt("si"+i.style.width, 65), apart from the base value. Does this mean I did it correctly? Thank you!

Hmm... Could you show all of your script? I think it would be easier to comment all in one. It is difficult to comment with only partial scripts. :(

Of course! Here's what I have so far.

    <html>
    <style>
    #playingArea {
        position: absolute;
        top: 1;
        left: 1;
        width: 750;
        height: 720;
        z-index: 2;
    }
    #basket {
        position: absolute;
        top: 650;
        left: 228;
        width: 100;
        height: 150;
    }
    </style>
    <script type="text/javascript" language="Javascript">
        var basket;
        var basketLeft = 228;

        function keyListener(e) {
            if (!e || (typeof(e)=="undefined")) { e = window.event; }
            if (e.keyCode==37 && basketLeft > 0) {
                basketLeft -= 8;
                basket.style.left = basketLeft + 'px' 
                for(i=0;i<grphcs.length;i++) {
                       if(parseInt(basket.style.left, 228) > Xpos[i] + parseInt("si"+i.style.width, 65) || parseInt(basket.style.left, 228) + parseInt(basket.style.width, 100) <
                       Xpos[i] || parseInt(basket.style.top, 650) > Ypos[i] + parseInt("si"+i.style.height, 84) || parseInt(basket.style.top, 650) + parseInt(basket.style.height,
                       150) < Ypos[i]) {
                           console.log("collision");
                       }
                }
            }

            if (e.keyCode==39 && basketLeft < 436){
                basketLeft += 8;
                basket.sty5le.left = basketLeft + 'px' ;
            }
        }

        function init() {
            basket=document.getElementById('basket');
            document.onkeydown=keyListener;
            fall();
        }

        grphcs=new Array(5)
        Image0=new Image();
        Image0.src=grphcs[0]="egg.png";
        Image1=new Image();
        Image1.src=grphcs[1]="egg_2.png";
        Image2=new Image();
        Image2.src=grphcs[2]="egg_3.png";
        Image3=new Image();
        Image3.src=grphcs[3]="egg_4.png";
        Image4=new Image();
        Image4.src=grphcs[4]="egg_5.png";

        Amount=5;
        Ypos=new Array();
        Xpos=new Array();
        Speed=new Array();
        Step=new Array();
        Cstep=new Array();
        var Stop=false;

        for(i=0;i<Amount;i++) {
            var P=Math.floor(Math.random()*grphcs.length);
            rndPic=grphcs[P];
            document.write('<img id="si'+i+'" src="'+rndPic+'"style="position:absolute;top:0px;left:0px">');
        }

        WinHeight=document.body.clientHeight;
        WinWidth=document.body.clientWidth;

        for(i=0;i<Amount;i++) {
            Ypos[i]=Math.round(Math.random()*WinHeight);
            Xpos[i]=Math.round(Math.random()*WinWidth);
            Speed[i]=Math.random()*5+3;
            Cstep[i]=0;
            Step[i]=Math.random()*0.1+0.05;
        }

        function fall() {
            if(Stop) {
            clear();
            return;
            }

            var WinHeight=document.body.clientHeight-100;
            var WinWidth=document.body.clientWidth-500;

            for(i=0;i<Amount;i++) {
                sy=Speed[i]*Math.sin(90*Math.PI/180);
                sx=Speed[i]*Math.cos(Cstep[i]);
                Ypos[i]+=sy;
                //Xpos[i]+=sx;
                if(Ypos[i]>WinHeight) {
                    Ypos[i]=60;
                    Xpos[i]=Math.round(Math.random()*WinWidth);
                    Speed[i]=Math.random()*5+3;
                }
                else
                {
                    document.getElementById("si"+i).style.left=Math.min(WinWidth,Xpos[i])-200;
                    document.getElementById("si"+i).style.top=Ypos[i];
                }

                Cstep[i]+=Step[i]; 

            }

            setTimeout('fall()',20);
        }

        setTimeout("Stop=true",30000);

        function clear() {
            for(i=0;i<Amount;i++)
            document.getElementById("si"+i).style.display='none';
        }

    </script>
    <body onload="init()";>

        <div id= "basket">
            <img src= "bottle.png">
        </div>

        <div id= "playingArea">

        </div>

    </body>
    </html>

OK, after looking through and tried the script, I am seeing at least a typo in line 39. Another problem is that you kept declaring a global variables (without using var in front of the variable). Another issue is how you name your variables. Please try to follow naming convension (camel case and start the variable name with a lower case).

Anyway, your design is a big issue here. You have "playingArea" element but non of your graphic is INSIDE the area? Also, you compute the display area using window's size, not the playingArea element? Also, you should consider to have your scripts inside a function rather than leave them outside all over the place...

One more issue is HTML syntax. When you declare style, you should use <style type="text/css"> instead of simply <style>. It is better to explicitly define the type property (without it, I had an issue displaying on Firefox). As a result, Javascript may not be able to correctly retrieve values from elements with specified style.

Anyway, I just realize that my suggestion to the old post is incomplete. What you should do in collision detection is to create another function. Then call the function after either an egg is moving or a key is pressed.

Below is only partial scripts I fixed. The variable names are changed to what the naming convension is as well.

// updated to keyListener() function
function keyListener(e) {
  if (!e || (typeof(e)=="undefined")) { e = window.event; }
  var pArea = document.getElementById("playingArea");
  if (e.keyCode==37 && basketLeft > 0) {  // key arrow - left
    basketLeft -= 8;
    basket.style.left = basketLeft + 'px' ;
    isCollide();  // after display, check if collide
  }
  else if (e.keyCode==39 && basketLeft < 436) {  // key arrow - right
    basketLeft += 8;
    basket.style.left = basketLeft + 'px' ;
    isCollide();  // after display, check all egg if collide
  }
}  // keyListener(Event)

// check if egg is collide (may return boolean if needed)
function isCollide(eggIdx) {
  var bWidth, bTop;
  var collide = false;

  if (window.getComputedStyle) {
    bWidth = parseInt(getComputedStyle(basket, null)["width"], 10);
    bTop = parseInt(getComputedStyle(basket, null)["top"], 10);
  }
  else {  // old IE
    bWidth = parseInt(basket.currentStyle["width"], 10);
    bTop = parseInt(basket.currentStyle["top"], 10);
  }

  if (isNaN(eggIdx) && eggIdx>=0 && eggIdx<grphcs.length) {  // given an egg to check
    var chkEgg = document.getElementById("si"+eggIdx);
    // part of the egg inside
    if(basketLeft <= xPos[eggIdx] &&  // left side of the basket position
       (basketLeft+bWidth) >= xPos[eggIdx] &&  // right side of the basket position
       (bTop-yPos[eggIdx]) < parseInt(chkEgg.style.height,10)) {
       console.log("collision: "+i);
       return true;
    }
  }  // end check 1 egg
  else {  // check all eggs
    for(var i=0;i<grphcs.length;i++) {
      var egg = document.getElementById("si"+i);
      if(basketLeft <= xPos[i] &&  // left side of the basket position
         (basketLeft+bWidth) >= xPos[i] &&  // right side of the basket position
         (bTop-yPos[i]) < -5) {  // part of the egg inside
         collide = true;
         console.log("collision: "+i);
      }
    }
  }  // end check all eggs
  return collide;
}  // isCollided(int)

// animation of falling eggs
function eggFall() {
  if(stopVal) {
    clear();
    return;
  }

  for(var i=0;i<Amount;i++) {
    sy=speed[i]*Math.sin(90*Math.PI/180);
    sx=speed[i]*Math.cos(cStep[i]);
    yPos[i]+=sy;
    //xPos[i]+=sx;
    // check if the egg falls off the display or collides with the basket
    if(yPos[i]>WinHeight || isCollide(i)) {
      yPos[i]=60;
      xPos[i]=Math.round(Math.random()*WinWidth);
      speed[i]=Math.random()*5+3;
    }
    else if (document.getElementById("si"+i)) {
      document.getElementById("si"+i).style.left=xPos[i]+"px";
      document.getElementById("si"+i).style.top=yPos[i]+"px";
    }
    cStep[i]+=step[i];
  }

  setTimeout(eggFall, 20);
}  // eggFall()

I got it to work as expected. However, the collision detection will be up to you to update. Currently, it only checks the top left of egg image is inside the basket. You may need a much better condition...

   function keyListener(e) {
      e = e || event; 
      if (e.keyCode==37 && basketLeft > 0) {
      ...

Hey, Taywin. Sorry for the radio silence. I think you may have lost me :S
I tried to apply your revised code but it doesn't seem to work. Can you tell me what went wrong? Thanks!

    <html>
    <style type="text/css">
    #playingArea {
        position: absolute;
        top: 1;
        left: 1;
        width: 750;
        height: 720;
        z-index: 2;
    }
    #basket {
        position: absolute;
        top: 650;
        left: 228;
        width: 100;
        height: 150;
    }
    </style>
    <script type="text/javascript" language="Javascript">
        var basket;
        var basketLeft = 228;
        function keyListener(e) {
          if (!e || (typeof(e)=="undefined")) { e = window.event; }
          var pArea = document.getElementById("playingArea");
          if (e.keyCode==37 && basketLeft > 0) {  // key arrow - left
            basketLeft -= 8;
            basket.style.left = basketLeft + 'px' ;
            isCollide();  // after display, check if collide
          }
          else if (e.keyCode==39 && basketLeft < 436) {  // key arrow - right
            basketLeft += 8;
            basket.style.left = basketLeft + 'px' ;
            isCollide();  // after display, check all egg if collide
          }
        } 

        grphcs=new Array(5)
        Image0=new Image();
        Image0.src=grphcs[0]="egg.png";
        Image1=new Image();
        Image1.src=grphcs[1]="egg_2.png";
        Image2=new Image();
        Image2.src=grphcs[2]="egg_3.png";
        Image3=new Image();
        Image3.src=grphcs[3]="egg_4.png";
        Image4=new Image();
        Image4.src=grphcs[4]="egg_5.png";

        Amount=5;
        Ypos=new Array();
        Xpos=new Array();
        Speed=new Array();
        Step=new Array();
        Cstep=new Array();
        Stop=false;

        function isCollide(eggIdx) {
          var bWidth, bTop;
          var collide = false;
          if (window.getComputedStyle) {
            bWidth = parseInt(getComputedStyle(basket, null)["width"], 10);
            bTop = parseInt(getComputedStyle(basket, null)["top"], 10);
          }
          else {  // old IE
            bWidth = parseInt(basket.currentStyle["width"], 10);
            bTop = parseInt(basket.currentStyle["top"], 10);
          }
          if (isNaN(eggIdx) && eggIdx>=0 && eggIdx<grphcs.length) {  // given an egg to check
            var chkEgg = document.getElementById("si"+eggIdx);
            // part of the egg inside
            if(basketLeft <= xPos[eggIdx] &&  // left side of the basket position
               (basketLeft+bWidth) >= xPos[eggIdx] &&  // right side of the basket position
               (bTop-yPos[eggIdx]) < parseInt(chkEgg.style.height,10)) {
               console.log("collision: "+i);
               return true;
            }
          }  // end check 1 egg
          else {  // check all eggs
            for(var i=0;i<grphcs.length;i++) {
              var egg = document.getElementById("si"+i);
              if(basketLeft <= xPos[i] &&  // left side of the basket position
                 (basketLeft+bWidth) >= xPos[i] &&  // right side of the basket position
                 (bTop-yPos[i]) < -5) {  // part of the egg inside
                 collide = true;
                 console.log("collision: "+i);
              }
            }
          }  // end check all eggs
          return collide;
        }  // isCollided(int)
        // animation of falling eggs
        function eggFall() {
          if(stopVal) {
            clear();
            return;
          }
          for(var i=0;i<Amount;i++) {
            sy=speed[i]*Math.sin(90*Math.PI/180);
            sx=speed[i]*Math.cos(cStep[i]);
            yPos[i]+=sy;
            //xPos[i]+=sx;
            // check if the egg falls off the display or collides with the basket
            if(yPos[i]>WinHeight || isCollide(i)) {
              yPos[i]=60;
              xPos[i]=Math.round(Math.random()*WinWidth);
              speed[i]=Math.random()*5+3;
            }
            else if (document.getElementById("si"+i)) {
              document.getElementById("si"+i).style.left=xPos[i]+"px";
              document.getElementById("si"+i).style.top=yPos[i]+"px";
            }
            cStep[i]+=step[i];
          }
          setTimeout(eggFall, 20);
        }  // eggFall()

        setTimeout("Stop=true",30000);

        function clear() {
            for(i=0;i<Amount;i++)
            document.getElementById("si"+i).style.display='none';
        }

    </script>
    <body onload="init()";>

        <div id= "playingArea">

            <div id= "basket">

                <img src= "bottle.png">

            </div>

        </div>

    </body>
    </html>

I had another glance at the code and made some adjustment. I'm now able to move the basket back and forth but the eggs are not falling. Can you tell me why?

    <html>
    <style type="text/css">
    #playingArea {
        position: absolute;
        top: 1;
        left: 1;
        width: 750;
        height: 720;
        z-index: 2;
    }
    #basket {
        position: absolute;
        top: 650;
        left: 228;
        width: 100;
        height: 150;
    }
    </style>
    <script type="text/javascript" language="Javascript">
    var basket;
    var basketLeft = 228;
    // updated to keyListener() function
    function keyListener(e) {
      if (!e || (typeof(e)=="undefined")) { e = window.event; }
      var pArea = document.getElementById("playingArea");
      if (e.keyCode==37 && basketLeft > 0) {  // key arrow - left
        basketLeft -= 8;
        basket.style.left = basketLeft + 'px' ;
        isCollide();  // after display, check if collide
      }
      else if (e.keyCode==39 && basketLeft < 436) {  // key arrow - right
        basketLeft += 8;
        basket.style.left = basketLeft + 'px' ;
        isCollide();  // after display, check all egg if collide
      }
    }  // keyListener(Event)
    function init()
    {
    basket=document.getElementById('basket');
    document.onkeydown=keyListener;
    eggFall();
    }
    grphcs=new Array(5)
    image0=new Image();
    image0.src=grphcs[0]="egg.png";
    image1=new Image();
    image1.src=grphcs[1]="egg_2.png";
    image2=new Image();
    image2.src=grphcs[2]="egg_3.png";
    image3=new Image();
    image3.src=grphcs[3]="egg_4.png";
    image4=new Image();
    image4.src=grphcs[4]="egg_5.png";
    Amount=5;
    yPos=new Array();
    xPos=new Array();
    speed=new Array();
    step=new Array();
    cStep=new Array();
    var stopVal=false;

    for(i=0;i<Amount;i++) {
        var P=Math.floor(Math.random()*grphcs.length);
        rndPic=grphcs[P];
        document.write('<img id="si'+i+'" src="'+rndPic+'"style="position:absolute;top:0px;left:0px">');
    }
    WinHeight=document.body.clientHeight;
    WinWidth=document.body.clientWidth;


    // check if egg is collide (may return boolean if needed)
    function isCollide(eggIdx) {
      var bWidth, bTop;
      var collide = false;

      if (window.getComputedStyle) {
        bWidth = parseInt(getComputedStyle(basket, null)["width"], 10);
        bTop = parseInt(getComputedStyle(basket, null)["top"], 10);
      }
      else {  // old IE
        bWidth = parseInt(basket.currentStyle["width"], 10);
        bTop = parseInt(basket.currentStyle["top"], 10);
      }

      if (isNaN(eggIdx) && eggIdx>=0 && eggIdx<grphcs.length) {  // given an egg to check
        var chkEgg = document.getElementById("si"+eggIdx);
        // part of the egg inside
        if(basketLeft <= xPos[eggIdx] &&  // left side of the basket position
           (basketLeft+bWidth) >= xPos[eggIdx] &&  // right side of the basket position
           (bTop-yPos[eggIdx]) < parseInt(chkEgg.style.height,10)) {
           console.log("collision: "+i);
           return true;
        }
      }  // end check 1 egg
      else {  // check all eggs
        for(var i=0;i<grphcs.length;i++) {
          var egg = document.getElementById("si"+i);
          if(basketLeft <= xPos[i] &&  // left side of the basket position
             (basketLeft+bWidth) >= xPos[i] &&  // right side of the basket position
             (bTop-yPos[i]) < -5) {  // part of the egg inside
             collide = true;
             console.log("collision: "+i);
          }
        }
      }  // end check all eggs
      return collide;
    }  // isCollided(int)

    // animation of falling eggs
    function eggFall() {
      if(stopVal) {
        clear();
        return;
      }

      for(var i=0;i<Amount;i++) {
        sy=speed[i]*Math.sin(90*Math.PI/180);
        sx=speed[i]*Math.cos(cStep[i]);
        yPos[i]+=sy;
        //xPos[i]+=sx;
        // check if the egg falls off the display or collides with the basket
        if(yPos[i]>WinHeight || isCollide(i)) {
          yPos[i]=60;
          xPos[i]=Math.round(Math.random()*WinWidth);
          speed[i]=Math.random()*5+3;
        }
        else if (document.getElementById("si"+i)) {
          document.getElementById("si"+i).style.left=xPos[i]+"px";
          document.getElementById("si"+i).style.top=yPos[i]+"px";
        }
        cStep[i]+=step[i];
      }

      setTimeout(eggFall, 20);
    }  // eggFall()

    setTimeout("Stop=true",30000);
           function clear() {
               for(i=0;i<Amount;i++)
               document.getElementById("si"+i).style.display='none';
           }
    </script>
    <body onload="init()";>

        <div id= "playingArea">

            <div id= "basket">

                <img src= "bottle.png">

            </div>

        </div>

    </body>
    </html>

Lines 62~68, they should be inside your init(). Also, once you move them inside, you need to change from document.write() to something that you need to create each image element instead. The reason is that document.write() will overwrite everything in your page if you put them inside a function (which is a proper way). You should not use document.write() because it is a one time deal and global.

for(i=0;i<Amount;i++) {
  var P=Math.floor(Math.random()*grphcs.length);
  rndPic=grphcs[P];
  document.write('<img id="si'+i+'" src="'+rndPic+'"style="position:absolute;top:0px;left:0px">');
}

// could be rewritten as
// obtain the playing area div element
var playArea = document.getElementById("playingArea");
for (var i=0; i<Amount; i++) {
  var elem = document.getElementById("si"+i);  // check if exist
  if (elem) {  // image exists, reset position
    elem.style.top = "0px";
    elem.style.left = "0px";
  }
  else {  // not exist, create element and add to display
    elem = document.createElement("img");
    elem.id = "si"+i;  // first time assignment
    elem.src = graphcs[Math.floor(Math.random()*graphcs.length)];
    elem.style.position = "absolute";
    elem.style.top = "0px";
    elem.style.left = "0px";
    playArea.append(elem);  // add the image to the playing area
  }
}

Sorry for all the back and forth. Everything seems to be functioning now but it's returning some potentially inaccurate info in my console. Can you confirm that this is due to the fact that the collision detection function needs to be adjusted as oppose to other errors in the code? Thanks!

    <html>
    <style type="text/css">
    #playingArea {
        position: absolute;
        top: 1;
        left: 1;
        width: 750;
        height: 720;
        z-index: 2;
    }
    #basket {
        position: absolute;
        top: 650;
        left: 228;
        width: 100;
        height: 150;
    }
    </style>
    <script type="text/javascript" language="Javascript">
    var basket;
    var basketLeft = 228;
    // updated to keyListener() function
    function keyListener(e) {
      if (!e || (typeof(e)=="undefined")) { e = window.event; }
      var pArea = document.getElementById("playingArea");
      if (e.keyCode==37 && basketLeft > 0) {  // key arrow - left
        basketLeft -= 8;
        basket.style.left = basketLeft + 'px' ;
        isCollide();  // after display, check if collide
      }
      else if (e.keyCode==39 && basketLeft < 436) {  // key arrow - right
        basketLeft += 8;
        basket.style.left = basketLeft + 'px' ;
        isCollide();  // after display, check all egg if collide
      }
    }  // keyListener(Event)
    function init() {
        basket=document.getElementById('basket');
        document.onkeydown=keyListener;
        eggFall();
    }
    grphcs=new Array(5)
    Image0=new Image();
    Image0.src=grphcs[0]="egg.png";
    Image1=new Image();
    Image1.src=grphcs[1]="egg_2.png";
    Image2=new Image();
    Image2.src=grphcs[2]="egg_3.png";
    Image3=new Image();
    Image3.src=grphcs[3]="egg_4.png";
    Image4=new Image();
    Image4.src=grphcs[4]="egg_5.png";
    Amount=5;
    yPos=new Array();
    xPos=new Array();
    speed=new Array();
    step=new Array();
    cstep=new Array();
    var stopVal=false;

    // check if egg is collide (may return boolean if needed)
    function isCollide(eggIdx) {
      var bWidth, bTop;
      var collide = false;

      if (window.getComputedStyle) {
        bWidth = parseInt(getComputedStyle(basket, null)["width"], 10);
        bTop = parseInt(getComputedStyle(basket, null)["top"], 10);
      }
      else {  // old IE
        bWidth = parseInt(basket.currentStyle["width"], 10);
        bTop = parseInt(basket.currentStyle["top"], 10);
      }

      if (isNaN(eggIdx) && eggIdx>=0 && eggIdx<grphcs.length) {  // given an egg to check
        var chkEgg = document.getElementById("si"+eggIdx);
        // part of the egg inside
        if(basketLeft <= xPos[eggIdx] &&  // left side of the basket position
           (basketLeft+bWidth) >= xPos[eggIdx] &&  // right side of the basket position
           (bTop-yPos[eggIdx]) < parseInt(chkEgg.style.height,10)) {
           console.log("collision: "+i);
           return true;
        }
      }  // end check 1 egg
      else {  // check all eggs
        for(var i=0;i<grphcs.length;i++) {
          var egg = document.getElementById("si"+i);
          if(basketLeft <= xPos[i] &&  // left side of the basket position
             (basketLeft+bWidth) >= xPos[i] &&  // right side of the basket position
             (bTop-yPos[i]) < -5) {  // part of the egg inside
             collide = true;
             console.log("collision: "+i);
          }
        }
      }  // end check all eggs
      return collide;
    }  // isCollided(int)

    // animation of falling eggs
      for(i=0;i<Amount;i++) {
               var P=Math.floor(Math.random()*grphcs.length);
               rndPic=grphcs[P];
               document.write('<img id="si'+i+'" src="'+rndPic+'"style="position:absolute;top:0px;left:0px">');
           }
           WinHeight=document.body.clientHeight;
           WinWidth=document.body.clientWidth;
           for(i=0;i<Amount;i++) {
               yPos[i]=Math.round(Math.random()*WinHeight);
               xPos[i]=Math.round(Math.random()*WinWidth);
               speed[i]=Math.random()*5+3;
               cstep[i]=0;
               step[i]=Math.random()*0.1+0.05;
           }
        function eggFall() {
          if(stopVal) {
            clear();
            return;
          }
               var WinHeight=document.body.clientHeight-100;
               var WinWidth=document.body.clientWidth-500;
               for(i=0;i<Amount;i++) {
                   sy=speed[i]*Math.sin(90*Math.PI/180);
                   sx=speed[i]*Math.cos(cstep[i]);
                   yPos[i]+=sy;
                   //xPos[i]+=sx;
                   if(yPos[i]>WinHeight) {
                       yPos[i]=60;
                       xPos[i]=Math.round(Math.random()*WinWidth);
                       speed[i]=Math.random()*5+3;
                   }
                   else
                   {
                       document.getElementById("si"+i).style.left=Math.min(WinWidth,xPos[i])-200;
                       document.getElementById("si"+i).style.top=yPos[i];
                   }
                   cstep[i]+=step[i]; 
               }
      setTimeout(eggFall, 20);
    }  // eggFall()

    function clear() {
        for(i=0;i<Amount;i++)
        document.getElementById("si"+i).style.display='none';
    }
    </script>
    <body onload="init()";>

        <div id= "playingArea">

            <div id= "basket">

                <img src= "bottle.png">

            </div>

        </div>

    </body>
    </html>

I showed you something. Please check it out.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.