PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 26, 2022

[FIXED] How to move items on the screen for a game using javascript?

 July 26, 2022     dreamweaver, html, javascript     No comments   

Issue

I want the img files to move across the screen and will disappear on click, after all are gone there will be a popup to show completion. However, only half my code works and the img files are stuck stationary.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>

   function runIt(me) {
      $(me).css("top",Math.random()*800)
      .animate({"left":"1200px"},Math.random()*3000+1500,function(){$(me).css("top",Math.random()*800)})
      .animate({"left":"-150px"},Math.random()*3000+1500,function(){$(me).css("top",Math.random()*800);runIt(me)});
   }
   $(".target").each(function(){runIt($(this))});

score = 0;
function calcScore(me){
  $(me).hide();
  score++;
  $("#message").html("You shot "+score);
  if(score==8){
    alert("You got all of them!");
  }
}
</script>
<body>
<div id="container">
<div id="background">
<div class="target" onclick="calcScore(this)"><img src="images/bottle.png" width="80" height="80" alt=""/></div>
<div class="target" onclick="calcScore(this)"><img src="images/bottle.png" width="80" height="80" alt=""/></div>
<div class="target" onclick="calcScore(this)"><img src="images/bottle.png" width="80" height="80" alt=""/></div>
<div class="target" onclick="calcScore(this)"><img src="images/bottle.png" width="80" height="80" alt=""/></div>
<div class="target" onclick="calcScore(this)"><img src="images/bottle.png" width="80" height="80" alt=""/></div>
<div class="target" onclick="calcScore(this)"><img src="images/bottle.png" width="80" height="80" alt=""/></div>
<div class="target" onclick="calcScore(this)"><img src="images/bottle.png" width="80" height="80" alt=""/></div>
<div class="target" onclick="calcScore(this)"><img src="images/bottle.png" width="80" height="80" alt=""/></div>
</div>
</div>
</body>

Solution

To fix it, Just add this css in your page

.target {
    position: absolute;
}

and put your trigger code $(".target").each(function(){runIt($(this))}); in document ready as below

$(document).ready(function(){
  $(".target").each(function(){runIt($(this))});
})


Answered By - Thanga
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing