0

I just created a animation task like simple game. When you click the start game button a circle will appear on random positions at certain intervals. i have tried my best and struggling to do the following tasks :

  • Add score +1 while click on the <p> (circle) element
  • Reduce score -1 while clicking rather than the <p> (circle) element

Thanks in advance.. :)

var windowHeight = 0;
var parendElement;

 function startg () {
    parendElement = document.getElementById("box");
    windowHeight = window.innerHeight;
    document.body.style.height = windowHeight + "px";

    var interval = setInterval(function () {
        generateBall();
    }, 1000);
};

function generateBall() {
    var leftPos = Math.floor((Math.random() * window.innerWidth) - 30);
    var topPos = Math.floor((Math.random() * windowHeight) - 30);
    var para = document.createElement("p");
    para.style.left = leftPos + "px";
    para.style.top = topPos + "px";
    para.setAttribute("class", 'circle');
    parendElement.appendChild(para);
    removeBall(para);
}
function removeBall(ele) {
    setTimeout(function () {
        parendElement.removeChild(ele);
    }, 1000);
}

var clicks= 0;
clicks = document.getElementById('scores').valueOf();

var ballclk = document.getElementsByClassName('circle');
ballclk.onclick = function (){
    clicks++;
    console.log('clicks');
};
.circle{
    width: 50px;
    height: 50px;
    border-radius: 30px;
    position: absolute;
    background-color: blueviolet;
}
body{
    overflow: hidden;
    position: relative;
}
#box{
    width: 100%;
    height: 100%;
}
.score{
    font-size: 18px;
    color: red;
    font-weight: bold;
}
input[type=text]
{
    padding: 5px 5px;
    font-weight: 600;
    font-size: 15px;
    width: 90px;
}
button{
    padding: 4px;
}
<body>
<div class="score">
<button onclick="startg()">Start Game</button>
<label for="scores"><b>Score</b></label>
<input type="text" value="0" name="scores" id="scores">
</div>
<div id="box"></div>
</body>

4 Answers 4

3

To expand on Mykola's answer, not only do you need to set the value in the field itself, but you also need to create the onclick event as you're creating the ball in generateBall() for it to work. Also the return value of valueOf() is the element itself, so you need to access the value then call parseInt() to convert it to a number.

For task #2, you can listen for clicks in the box div, but you need to have your p clicks call stopPropagation() so that their clicks don't bubble to the div, preventing your score from changing.

Modified code below:

var windowHeight = 0;
var parendElement;
var gameStarted = false;
var clicks;

function startg() {
  parendElement = document.getElementById("box");
  gameStarted = true;
  windowHeight = window.innerHeight;
  document.body.style.height = windowHeight + "px";
  clicks = parseInt(document.getElementById('scores').value)

  parendElement.onclick = function() {
    if (gameStarted) {
      document.getElementById('scores').value = --clicks;
    }
  };

  var interval = setInterval(function() {
    generateBall();
  }, 1000);
};

function generateBall() {
  var leftPos = Math.floor((Math.random() * window.innerWidth) - 30);
  var topPos = Math.floor((Math.random() * windowHeight) - 30);
  var para = document.createElement("p");
  para.style.left = leftPos + "px";
  para.style.top = topPos + "px";
  para.setAttribute("class", 'circle');
  para.onclick = function(e) {
    e.stopPropagation();
    document.getElementById('scores').value = ++clicks;
    console.log('clicks');
  };
  parendElement.appendChild(para);
  removeBall(para);
}

function removeBall(ele) {
  setTimeout(function() {
    parendElement.removeChild(ele);
  }, 1000);
}
.circle {
  width: 50px;
  height: 50px;
  border-radius: 30px;
  position: absolute;
  background-color: blueviolet;
}
body {
  overflow: hidden;
  position: relative;
}
#box {
  width: 100%;
  height: 100%;
}
.score {
  font-size: 18px;
  color: red;
  font-weight: bold;
}
input[type=text] {
  padding: 5px 5px;
  font-weight: 600;
  font-size: 15px;
  width: 90px;
}
button {
  padding: 4px;
}
<body>
  <div class="score">
    <button onclick="startg()">Start Game</button>
    <label for="scores"><b>Score</b>
    </label>
    <input type="text" value="0" name="scores" id="scores">
  </div>
  <div id="box"></div>
</body>

Sign up to request clarification or add additional context in comments.

7 Comments

Working gud for task one.. Got idea for task two.. I'll create that.. Thanks :)
Fast? I didn't even have my coffee yet, but thanks. :) @PrasathV, you're welcome. Task #2 should be pretty simple to add, but just be aware of event propagation when trying to capture misclicks.
I'm getting this error Uncaught TypeError: Cannot read property 'valueOf' of null and input field shows NaN @xorspark
Check your markup? Also, are you running after the document has fully loaded or in the head before the markup occurs?. Works fine in the snippet.
I moved the clicks value initialization into the start game method and added how to accomplish #2.
|
2

You have created the p element but you didn't added the click event to it which causes for the

Add this to the generateBall Methods

 para.onclick = function() {
    document.getElementById('scores').value = ++clicks;
    console.log('clicks');
  };

So here is the working fiddle

1 Comment

@prasath just a small suggestion try to add cursor:pointer for class circle will change the pointer.
1

updated with .stopPropagation() (thank you @xorspark)

Here you go, with -1 for clicks outside the circle, but I don't think this is the right way to do it, I added 2 instead of 1 to the click event of the circle as a workaround because I couldn't get the selector body:not(.circle) to work.

also (as mentioned by @Mykola_Borysyuk) you should use:

document.getElementById('scores').value = clicks;

instead of

clicks = document.getElementById('scores').valueOf();

because you're taking the value of clicks and putting it in the input, not the other way around.

good start though :)

var windowHeight = 0;
		var parendElement;
		var clicks = 0;
		clicksInput = document.getElementById('scores');

		 function startg () {
		    parendElement = document.getElementById("body")
		    windowHeight = window.innerHeight;
		    document.body.style.height = windowHeight + "px";
			
		    var interval = setInterval(function () {
		        generateBall();
		    }, 1000);
		};

		function generateBall() {
		    var leftPos = Math.floor((Math.random() * window.innerWidth) - 30);
		    var topPos = Math.floor((Math.random() * windowHeight) - 30);
			document.getElementById('box').onclick = function(e){e.stopPropagation();score('-')}
		    var para = document.createElement("p");
		    para.style.left = leftPos + "px";
		    para.style.top = topPos + "px";
		    para.setAttribute("class", 'circle');
		    parendElement.appendChild(para);
			para.onclick = function(){score('+')}
			
		    removeBall(para);
		}
		function removeBall(ele) {
		    setTimeout(function () {
		        parendElement.removeChild(ele);
		    }, 1000);
		}

		function score(operation) {
			if (operation == '+') {
				clicks++;
				clicksInput.value = clicks;
				console.log('clicks');
			} else {
				clicks--;
				clicksInput.value = clicks;
				console.log('clicks');
			}
		}
.circle{
    width: 50px;
    height: 50px;
    border-radius: 30px;
    position: absolute;
    background-color: blueviolet;
}
body{
    overflow: hidden;
    position: relative;
}
#box{
    width: 100%;
    height: 100%;
}
.score{
    font-size: 18px;
    color: red;
    font-weight: bold;
}
input[type=text]
{
    padding: 5px 5px;
    font-weight: 600;
    font-size: 15px;
    width: 90px;
}
button{
    padding: 4px;
}
<body id="body">
<div class="score">
<button onclick="startg()">Start Game</button>
<label for="scores"><b>Score</b></label>
<input type="text" value="0" name="scores" id="scores">
</div>
<div id="box"></div>
</body>

1 Comment

You can just call stopPropagation on the click event so you don't have to add twice.
1

You just need to change input value after each click. So in function generateBall just add :

document.getElementById('scores').value = clicks;

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.