Progress Bar Keeps Repeating - javascript

How can the code below be modified such that when the progress bar is finished loading and it reaches the end, a seperate function (ie. test() )can be executed rather than just repeating and repeating like it is now.
<html>
<head>
<script type="text/javascript">
var prg_width = 200;
function progress() {
var node = document.getElementById('progress');
var w = node.style.width.match(/\d+/);
if (w == prg_width) {
w = 0;
}
node.style.width = parseInt(w) + 5 + 'px';
}
</script>
</head>
<body onload="var progress_run_id = setInterval(progress, 30);">
<div style="border: 1px solid #808080; width:200px; height:5px;">
<div id="progress" style="height:5px; width:0px; background-color:#DBDBDB;"/>
</div>
</body>
</html>
Much thanks and appreciation for all your help.
Cheers,
Jay

Call this separate function instead of
w = 0;
line. Don't forget to clearInterval(progress_run_id) too.

<html>
<head>
<script type="text/javascript">
var prg_width = 200;
var progress_run_id = null;
function progress() {
var node = document.getElementById('progress');
var w = node.style.width.match(/\d+/);
if (w == prg_width) {
clearInterval( progress_run_id );
w = 0;
} else {
w = parseInt(w) + 5 + 'px';
}
node.style.width = w;
}
function initialize(){
progress_run_id = setInterval(progress, 30);
}
window.onload = initialize();
</script>
</head>
<body>
<div style="border: 1px solid #808080; width:200px; height:5px;">
<div id="progress" style="height:5px; width:0px; background-color:#DBDBDB;"/>
</div>
</body>
</html>

var prg_width = 200;
function progress() {
var node = document.getElementById('progress');
var w = node.style.width.match(/\d+/);
if (w == prg_width) {
test(); // CHANGE THIS
clearInterval(progress_run_id);
}
node.style.width = parseInt(w) + 5 + 'px';
}
That checks if the width is equal to the completed width. If it is, then clear the interval, and call your test function.

<script type="text/javascript">
var prg_width = 200;
function progress() {
var node = document.getElementById('progress');
var w = node.style.width.match(/\d+/);
if (w == prg_width) {
test();
clearInterval(progress_run_id);
}
node.style.width = parseInt(w) + 5 + 'px';
}
</script>

Related

Js animate a ball wrong, slow then faster everytime

When I run this code first time the animation speed is slow, then every time faster.The code moves a ball, and after you touch the screen, the ball goes to where you touched.
But the first time, it is very slow, then every time it goes faster. Why?
I was expecting a similar speed, not perfectly constant, but not like that.
Also on the tenth attempt the ball goes too fast.
I try on my smartphone, I don't know if it will work on a computer.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.point{
width:10px; height:10px;
background-color:green;
position:absolute;
}
#ball{
width:10px; height:10px;
background-color:red;
position:absolute;
top:1px; left:50px;
}
</style>
</head>
<body>
<div class="point"></div>
<div id="ball"></div>
<script type="text/javascript">
window.addEventListener("touchstart", function(e){
var cx = e.touches[0].clientX;
var cy = e.touches[0].clientY;
});
window.addEventListener("touchmove", function(e){
var cx = e.touches[0].clientX;
var cy = e.touches[0].clientY;
endB = [cx, cy];
});
window.addEventListener("touchend", function(e){
decl();
});
function decl(){
isBmove = true;
mstep = 2;
requestAnimationFrame(step);
}
function step(ts){
if (isBmove){
var dfrein = 25;
var gb = b.getBoundingClientRect();
var ang = Math.atan2(endB[1]-gb.top, endB[0]-gb.left);
var addX = Math.cos(ang)*mstep;
var addY = Math.sin(ang)*mstep;
var difX = endB[0]-gb.left;
var difY = endB[1]-gb.top;
var dist = Math.sqrt(Math.pow(difX,2),Math.pow(difY,2));
if(dist < dfrein){
mstep *= 0.98;
l("m= "+mstep);
}
if (mstep < 1){
isBmove = false;
l("add :"+addX+","+addY);
}
b.style.top = gb.top+addY+"px";
b.style.left = gb.left+addX+"px";
}
requestAnimationFrame(step);
}
window.requestAnimationFrame =
window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.msRequestAnimationFrame;
var isBmove = false;
var endB = [0,0];
var mstep = 2;
var b = document.getElementById("ball");
function l(p){
console.log(p);
}
</script>
</body>
</html>
Thanks
If I am not mistaken, it is because you require a new animation frame everytime you call your touchend event listener, that way calling the decl() function. So, maybe try getting the requestAnimationFrame(step) out of the decl(). Like so:
// Instead of:
function decl(){
isBmove = true;
mstep = 2;
requestAnimationFrame(step);
}
// Try like this:
function decl() {
isBmove = true;
mstep = 2;
}
requestAnimationFrame(step)
Petar is correct. For what it's worth, here's a version of your app changed to work on mouse events.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.point {
width: 10px;
height: 10px;
background-color: green;
position: absolute;
}
#ball {
width: 10px;
height: 10px;
background-color: red;
position: absolute;
top: 1px;
left: 50px;
}
</style>
</head>
<body>
<div class="point"></div>
<div id="ball"></div>
<script type="text/javascript">
window.addEventListener("mousedown", function (e) {
var cx = e.clientX;
var cy = e.clientY;
});
window.addEventListener("mousemove", function (e) {
var cx = e.clientX;
var cy = e.clientY;
endB = [cx, cy];
});
window.addEventListener("mouseup", function (e) {
decl();
});
function decl() {
isBmove = true;
mstep = 2;
}
function step(ts) {
if (isBmove) {
var dfrein = 25;
var gb = b.getBoundingClientRect();
var ang = Math.atan2(endB[1] - gb.top, endB[0] - gb.left);
var addX = Math.cos(ang) * mstep;
var addY = Math.sin(ang) * mstep;
var difX = endB[0] - gb.left;
var difY = endB[1] - gb.top;
var dist = Math.sqrt(Math.pow(difX, 2), Math.pow(difY, 2));
if (dist < dfrein) {
mstep *= 0.98;
l("m= " + mstep);
}
if (mstep < 1) {
isBmove = false;
}
l("add :" + addX + "," + addY);
b.style.top = gb.top + addY + "px";
b.style.left = gb.left + addX + "px";
}
requestAnimationFrame(step);
}
requestAnimationFrame(step);
window.requestAnimationFrame =
window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.msRequestAnimationFrame;
var isBmove = false;
var endB = [0, 0];
var mstep = 2;
var b = document.getElementById("ball");
function l(p) {
console.log(p);
}
</script>
</body>
</html>

storing high score with javascript

I have practiced one question and this is about checking time to click the shape that comes up. I want to save the the high score and compare with the next one coming up. It is just how to store the high score . It would be great help if somebody give the way to do it. Thank you in advance
<!doctype html>
<html>
<head>
<title> Javasript </title>
<style type="text/css">
#shape {
width: 200px;
height: 200px;
display:none;
position : relative;
}
</style>
</head>
<body>
<h1>Test your reaction </h1>
<p>Click on the boxes as soon as possible and win it </p>
<p>Your time taken <span id="timeTaken"></span></p>
<div id="shape"></div>
<script type="text/javascript">
var start = new Date().getTime();
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function makeShapeAppear() {
var top = Math.random() * 400 ;
var left = Math.random() * 400 ;
var width = (Math.random() * 200) + 100 ;
if (Math.random()> 0.5) {
document.getElementById("shape").style.borderRadius = "50%";
} else {
document.getElementById("shape").style.borderRadius = "0%"; }
document.getElementById("shape").style.backgroundColor = getRandomColor();
document.getElementById("shape").style.height = top + 'px';
document.getElementById("shape").style.width = width + 'px';
document.getElementById("shape").style.top = top + 'px';
document.getElementById("shape").style.left = left + 'px';
document.getElementById("shape").style.height = top + 'px';
document.getElementById("shape").style.display = 'block';
start = new Date().getTime();
}
function appearAfterDelay() {
setTimeout(makeShapeAppear, Math.random() * 2000 );
}
appearAfterDelay();
document.getElementById("shape").onclick = function() {
document.getElementById("shape").style.display = 'none';
var end = new Date().getTime();
var timeTaken = (end - start)/1000;
document.getElementById("timeTaken").innerHTML = timeTaken + "s";
appearAfterDelay();
}
</script>
</body>
</html>

Dom html javascript about onclick

I want to generate five image imgs first in left side, then remove the lastchild of it and copy the rest to the right side. If user clicks the extra img in left side, then clear all and generate more 5(10) img in left and copy 9 to the right side, and so on. If user clicks the wrong place, alert ("game over").Here is my code:
<html>
<head>
<style>
img{
position: absolute;
}
div{
position: absolute;
width: 500px;
height: 500px;
}
#rightSide { left: 500px;
border-left: 1px solid black;
}
</style>
<script>
var numberOfFaces = 5;
function generateFaces(){
var theLeftSide = document.getElementById("leftSide");
for (var i = 0; i < numberOfFaces; i++){
var img = document.createElement("img");
img.src = "smile.png";
var randomTop = Math.random() * 400;
var randomLeft = Math.random() * 400;
img.style.top = randomTop + "px";
img.style.left = randomLeft + "px";
theLeftSide.appendChild(img);
}
var theRightSide = document.getElementById("rightSide");
leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
document.getElementById("rightSide").appendChild(leftSideImages);
var theBody = document.getElementByTagName("body")[0];
theLeftSide.lastChild.onclick = function nextLevel(event){
event.stopPropagation();
while (theBody.firstChild){
theBody.removeChild(theBody.firstChild);
}
numberOfFaces += 5;
generateFaces();
}
theBody.onclick = function gameover(){
alert("Game Over");
thBody.onclick = null;
theLeftSide.lastChild.onclick = null;
}
}
window.onload = generateFaces;
</script>
</head>
<body>
<h1>Matching Game</h1>
<p>click on the extra smiling face on the left</p>
<div id = "leftSide">
</div>
<div id = "rightSide">
</div>
</body>
</html>
I could generate and clone at first time, but when I click, nothing happens, so what is the problem?
This may be a typing error.
var theBody = document.getElementsByTagName("body")[0];
your code: var theBody = document.getElementByTagName("body")[0];
I suggest to use a good editor for html. I fixed the error with Jetbrain phpStorm but better ones may exist.
Bellow is a modified version that worked for me. Notice that in this version I added the events on all children instead of the whole document body. I don't know but for me it feels more accurate not to end the game on a user clicks on a white space for example.
<html>
<head>
<style>
img{
position: absolute;
}
div{
position: absolute;
width: 500px;
height: 500px;
}
#rightSide { left: 500px;
border-left: 1px solid black;
}
</style>
<script>
var numberOfFaces = 5;
var theBody;
var theLeftSide;
var theRightSide;
function generateFaces(){
theBody = document.getElementsByTagName("body")[0];
theLeftSide = document.getElementById("leftSide");
theRightSide = document.getElementById("rightSide");
for (var i = 0; i < numberOfFaces; i++){
var img = document.createElement("img");
img.src = "smile.png";
var randomTop = Math.random() * 400;
var randomLeft = Math.random() * 400;
img.style.top = randomTop + "px";
img.style.left = randomLeft + "px";
if(theLeftSide != null)
theLeftSide.appendChild(img);
else
{
alert("Game Over");
return;
}
}
var leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
document.getElementById("rightSide").appendChild(leftSideImages);
addEvents();
}
function addEvents(){
for(var i=0; i < theLeftSide.childNodes.length; i++){
theLeftSide.childNodes[i].onclick = nextLevel;
}
}
function removeEvents(){
for(var i=0; i < theLeftSide.childNodes.length; i++){
theLeftSide.childNodes[i].onclick = null;
}
}
function nextLevel(event){
if(this == theLeftSide.lastChild){
event.stopPropagation();
theLeftSide.innerHTML = "";
theRightSide.innerHTML = "";
numberOfFaces += 5;
generateFaces();
}
else
{
alert("Game Over");
removeEvents();
}
}
window.onload = generateFaces;
</script>
</head>
<body>
<h1>Matching Game</h1>
<p>click on the extra smiling face on the left</p>
<div id = "leftSide">
</div>
<div id = "rightSide">
</div>
</body>
</html>

update .style attributes with setInterval

I'm trying to move the position of a div element at set intervals however the setInterval method executes once and then stops. setInterval() doesn't update .style.transform repeatedly every 200 milliseconds as intended.
<!DOCTYPE html>
<html>
<head>
<title>Snake game</title>
<style type="text/css">
.container {
width: 500px;
height: 500px;
border: 2px solid black;
}
#snakehead {
width: 5px;
height: 5px;
background: pink;
position: relative;
left: 0px;
}
</style>
<script type="text/javascript" src="snake.js"></script>
</head>
<body>
<div class="container">
<div id="snakehead"></div>
</div>
</body>
</html>
Javascript: Ideally I'd also like to be able to move the snakehead in any direction with vx and vy. Anyway to put those values into .style.transform = translateX()?
function snakepos() {
var x = 0;
var y = 0;
var vx = 1;
var vy = 0;
return {
move: function() {
x += vx;
y += vy;
var snakehead = document.querySelector("#snakehead");
snakedhead.style.left = "5px";
}
};
}
window.onload = function() {
console.log("hi");
var container = document.querySelector(".container");
var snake = snakepos();
setInterval(function() {
snake.move();
}, 200);
}
I know this can be done much easier in jQuery with .css but I'd to how this can be done in vanilla javascript. Thank you in advance.
snakehead.style.left = (snakedhead.style.left + "5px");
or
snakehead.style.left = (snakedhead.style.left - "5px");
I'd recommend something in a style a bit more familiar to me:
function snakepos() {
this.x = 0;
this.y = 0;
this.vx = 1;
this.vy = 1;
this.snakehead = document.querySelector("#snakehead");
var me = this;
this.move = function() {
me.x += me.vx;
me.y += me.vy;
me.snakehead.style.top = me.y + "px";
me.snakehead.style.left = me.x + "px";
};
return this;
}
console.log("hi");
var container = document.querySelector(".container");
var snake = new snakepos();
setInterval(function() {
snake.move();
}, 200);
See fiddle: https://jsfiddle.net/theredhead/td8opb0b/1/

Change div width every 1 second by 5px

I tried to change div width every 1 second by 5px using JavaScript. How can I make this work?
Here's my code:
<html>
<head>
<title>JS Functions</title>
</head>
<body>
<div style="width:100px; height:100px; background:gray" id="box" onclick="bigger()"></div>
<script>
function bigger()
{
var w = 100
var h = 100
while(w < 1000, h < 1000)
{
w = w+5;
h = h+5;
document.getElementById('box').style.width = w
document.getElementById('box').style.height = h
setInterval();
}
}
</script>
</body>
</html>
No while loop needed. You can just use setInterval:
var w = 100;
var h = 100;
var foo = setInterval(function () {
if(w>1000) cancelInterval(foo)
w = w + 5;
h = h + 5;
document.getElementById('box').style.width = w + 'px';
document.getElementById('box').style.height = h + 'px';
}, 1000);
<div style="width:100px; height:100px; background:gray" id="box" onclick="bigger()"></div>
You need to use setInterval to call your code every second, so move it outside of the bigger() function. Also you need the full value for style, including the unit you're using.
try this
<html>
<head>
<title>JS Functions</title>
</head>
<body>
<div style="width:100px; height:100px; background:gray" id="box"></div>
<script>
var w = 100;
var h = 100;
function bigger()
{
if (w < 1000 && h < 1000)
{
w = w+5;
h = h+5;
document.getElementById('box').style.width = w + 'px';
document.getElementById('box').style.height = h + 'px';
} else {
clearInterval(int);
}
}
var int = setInterval(bigger, 1000);
</script>
</body>
</html>
Let's say you have a div wth id='boxToEnlarge'
The JSFiddle: http://jsfiddle.net/7qtb1u8e/1/
And this is the actual code:
function enlargeBox(){
//get current size
var currentWidth = document.getElementById('boxToEnlarge').offsetWidth;
var currentHeight = document.getElementById('boxToEnlarge').offsetHeight;
//add 5 more pixels to current size
document.getElementById('boxToEnlarge').style.width = currentWidth + 5 +'px';
document.getElementById('boxToEnlarge').style.height = currentHeight + 5 +'px';
}
//call the enlargeBox func every 1 sec (1000 milliseconds)
setInterval(function(){enlargeBox()},1000);
We are reading the current size of the div we want to enlarge then we add 5px to that amount and apply it on it's width/height CSS properties.
We wrap the above in a function and using setInterval, we call that function once every n milliseconds, in this case 1000ms which equals 1 second

Categories