Javascript - Animation only working the first time the button is pressed - javascript

I have an animation which is called using onmousedown. I have another function which stops the animation (onmouseup).
The problem is that it only works the first time. By that I mean when I hold the button, it works and then stops when I stop pressing down but if I try to use either of the buttons after that first time nothing happens. It just won't move.
This is my HTML code (index.htm):
<html>
<head><link rel='stylesheet' href='style.css'></head>
<body>
<img id='player' src='img/player.png' style='height:64px;'></img>
<div class='buttons'>
<button id='moveleft' onmousedown="OnButtonDownl (this)" onmouseup="OnButtonUpl (this)"><--</button>
<button id='moveright' onmousedown="OnButtonDownr (this)" onmouseup="OnButtonUpr (this)">--></button>
</div>
</body>
</html>
<script type='text/javascript' src='move.js'></script>
This is my javascript code (move.js):
var elem = document.getElementById("player");
function OnButtonDownl (button) {
var posl = document.getElementById("player").style.left;
window.idl = setInterval(framel, 5);
function framel() {
posl--;
elem.style.left = posl + 'px';
}}
function OnButtonUpl (button) {
clearInterval(idl);
}
var elem = document.getElementById("player");
function OnButtonDownr (button) {
var posr = document.getElementById("player").style.left;
window.idr = setInterval(framer, 5);
function framer() {
posr++;
elem.style.left = posr + 'px';
}}
function OnButtonUpr (button) {
clearInterval(idr);
}
Probably not important but here is my css (style.css):
body {
width: 100%;
height: 100%;
position:relative;
margin:0;
overflow:hidden;
}
#player {
position: absolute;
left:0;
bottom:0;
}
.buttons {
position:absolute;
right:0;
bottom:0;
}
Thanks for any help in advance.

You're running into 2 issues.
When you first get posl and posr, you're getting an empty string that JS is coercing to 0.
The -- and ++ won't work after you append the px (thus making posl and posr into string values)
Your posl-- (and posr++) can increment that coerced 0. That's why it works the first time through. The next time you mousedown the document.getElementById("player").style.left is a string — like "-1px" — that isn't interpreted as falsy (won't be coerced into 0). You can get around that by using parseInt() when you cache posl|posr but you have to provide a fallback of 0 because parseInt("") returns NaN…
You can work around that like so (with similar changes when you get posr):
var posl = parseInt( document.getElementById("player").style.left, 10 ) || 0;
var elem = document.getElementById("player");
function OnButtonDownl(button) {
//var posl = document.getElementById("player").style.left;
var posl = parseInt(document.getElementById("player").style.left, 10) || 0;
window.idl = setInterval(framel, 5);
function framel() {
posl--;
elem.style.left = posl + 'px';
}
}
function OnButtonUpl(button) {
clearInterval(idl);
}
var elem = document.getElementById("player");
function OnButtonDownr(button) {
//var posr = document.getElementById("player").style.left;
var posr = parseInt(document.getElementById("player").style.left, 10) || 0;
window.idr = setInterval(framer, 5);
function framer() {
posr++;
elem.style.left = posr + 'px';
}
}
function OnButtonUpr(button) {
clearInterval(idr);
}
body {
width: 100vw;// changed for example only
height: 100vh;// changed for example only
position: relative;
margin: 0;
overflow: hidden;
}
#player {
position: absolute;
left: 0;
bottom: 0;
}
.buttons {
position: absolute;
right: 0;
bottom: 0;
}
<img id='player' src='//placekitten.com/102/102' />
<div class='buttons'>
<button id='moveleft' onmousedown="OnButtonDownl (this)" onmouseup="OnButtonUpl (this)">Left</button>
<button id='moveright' onmousedown="OnButtonDownr (this)" onmouseup="OnButtonUpr (this)">Right</button>
</div>

I was rewrite your code and it work (for me).
function Move(elem){
this.interval;
var posr = parseInt(getComputedStyle(document.getElementById("player")).left);
this.handleEvent = function(event) {
switch (event.type) {
case 'mousedown':
this.interval = setInterval(function() {
if (event.target.id == 'moveright') {
posr++;
} else if (event.target.id == 'moveleft'){
posr--;
}
document.getElementById("player").style.left = posr + 'px';
},5);
break;
case 'mouseup':
clearInterval(this.interval);
break;
}
}
elem.addEventListener('mousedown', this, false);
elem.addEventListener('mouseup', this, false);
}
var button_right = document.getElementById("moveright");
var button_left = document.getElementById("moveleft");
Move(button_right);
Move(button_left);
And in html you can remove js event listeners (this need only id).

First of all it is good practice to put your script tag inside your html tags:
<html>
<head>...</head>
<body>...</body>
<script type='text/javascript' src='move.js'></script>
</html>
Done that check this solution:
HTML:
<html>
<head><link rel='stylesheet' href='style.css'></head>
<body>
<img id='player' src='https://placeimg.com/54/45/any' style='height:64px;'></img>
<div class='buttons'>
<button id='moveleft' onmousedown="OnButtonDown('left')" onmouseup="OnButtonUp()"><--</button>
<button id='moveright' onmousedown="OnButtonDown('right')" onmouseup="OnButtonUp()">--></button>
</div>
<script type='text/javascript' src='move.js'></script>
</body>
</html>
And js:
var nIntervId;
var b;
var elem = document.getElementById("player");
var posl = document.getElementById("player").style.left;
function OnButtonDown(button) {
b = button;
nIntervId = setInterval(frame, 5);
}
function frame() {
if(b==='left'){
posl--;
elem.style.left = posl + 'px';}
else{
posl++;
elem.style.left = posl + 'px';
}
}
function OnButtonUp() {
clearInterval(nIntervId);
}
http://output.jsbin.com/varaseheru/

Related

Starting second javascript when the first one is finished

I'm working on a progress bar. It has a label. I want to adjust that label a certain script is finished. After finding some answers of probable solution, I came up with the following script. The first initiates and works as expected. However, the second one doesn't. What's wrong with it? Here's the code:
HTML:
<form method ="post">
<input class=generate type="submit" value="Upload" onclick="move();finalize()"/>
</form>
Javascript:
<script>
function move() {
var elem = document.getElementById("myBar");
var myFunc01 = function() {
var i = 1;
while (i < 101) {
(function(i) {
setTimeout(function() {
i++;
elem.style.width = i + '%';
elem.innerHTML = i + '%';
}, 600 * i)
})(i++)
}
};
myFunc01();
}
</script>
<script>
function finalize() {
var elem = document.getElementById("myBar");
var myFunc02 = function() {
elem.innerHTML = 'Finalizing...';
};
setTimeout(myFunc02, 600);
}
</script>
var elem = document.querySelector('#myBar');
function done() {
elem.innerText = 'UPLOAD HAS FINISHED';
}
var upload = function(callback) {
var width = 1;
var id;
var frame = function() {
if (width >= 100) {
clearInterval(id);
callback();
} else {
width++;
elem.style.width = width + '%';
}
};
id = setInterval(frame, 10);
};
/*
upload(function() {
elem.innerText = 'UPLOAD HAS FINISHED';
});
*/
#myProgress {
width: 100%;
background-color: grey;
}
#myBar {
width: 1%;
height: 30px;
background-color: green;
text-align: center;
line-height: 27px;
}
<button onclick="upload(done)">START UPLOAD</button>
<div id="myProgress">
<div id="myBar"></div>
</div>
You could use a callback. A callback is a function that runs upon completion.
function move(callback) {
//code you want to happen first
}
move(function(){
//code you want to have happen after completion
})
thats the basic idea of how a simple callback works
Thanks James, that's it!
After some re-arranging, this is what the second script looks like. And it works as expected.
<script>
function finalize() {setTimeout(function(){
var elem = document.getElementById("myBar");
var myFunc02 = function() {
elem.innerHTML = 'Finalizing...';
};
myFunc02();
}
, 600);}
</script>

Unable to declare variable in onload attribute

I was creating a web page, in which an image moves horizontally until the 'stop me' button is pressed.
<html>
<head>
<script>
var count = 0;
function move(){
image = document.getElementsByTagName("img")[0];
count++;
image.style.left = count;
}
</script>
</head>
<body onload = "var temp = setInterval(move,1)">
<img src = "facebook_icon.png" style = "position:absolute; left = 0; top:0;">
<br>
<button onclick = "clearInterval(temp);">Click here to stop the loop.</button>
</body>
</html>
when I remove the var keyword from the onload attribute, the code runs fine.
New code:-
<html>
<head>
<script>
var count = 0;
function move(){
image = document.getElementsByTagName("img")[0];
count++;
image.style.left = count;
}
</script>
</head>
<body onload = "temp = setInterval(move,1)">
<img src = "facebook_icon.png" style = "position:absolute; left = 0; top:0;">
<br>
<button onclick = "clearInterval(temp);">Click here to stop the loop.</button>
</body>
</html>
Why is it so?
It's a scope issue: variables declared in the attribute are not global, example:
<body onload = "var temp = 'hello'; alert(temp);">
<button onclick = "alert(temp);">Click</button>
</body>
In the above example, on page load, an alert will show the message hello. But, when you click the button you get this error Uncaught ReferenceError: temp is not defined. This means that the variable temp is not accessible (not global).
However, assigning a value to an undeclared variable implicitly creates it as a global variable, that's why your second example works fine:
Try this one.
CSS
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
</style>
HTML
<div id="container">
<img src="images/up.png" id="animate" />
</div>
<br/>
<br/>
<br/>
<button onclick="myStopFunction()">Click here to stop the loop.</button>
Script
<script type="text/javascript">
function myMove() {
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 1);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
function myStopFunction() {
var elem = document.getElementById("animate");
clearInterval(myMove());
}
</script>

Using on click vanilla JS, activating on wrong node

Almost finished this sort of game i am working on to learn Dom manipulation. Basically the game spawns 5 images on the left and 4 on the right, you click the odd one out and then 10 spawn on the left and 9 on the right(+5 everytime).
I am wanting my nextlevel function to work every time the last child(of theLeftSide) is clicked on. It works the first time but after that regardless of if i click the correct node or not, my gameOver function is called and im not sure why. I tried removing the game over function and still the 2nd time i want my nextLevel to run(after click), it doesnt. Am i going about this the totally wrong way? Any input is appreciated thank you. Left my gameOver function in so you can see what im trying to do with it.
var theLeftSide = document.getElementById("leftside");
var theRightSide = document.getElementById("rightside");
var facesNeeded = 5;
var totalfFaces = 0;
var theBody = document.getElementsByTagName("body")[0];
function makeFaces() {
while (facesNeeded != totalfFaces) {
smiley = document.createElement("img");
smiley.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
smiley.style.top = Math.random() * 401 + "px";
smiley.style.left = Math.random() * 401 + "px";
document.getElementById("leftside").appendChild(smiley);
totalfFaces++;
// alert(totalfFaces); used to debug
}
if (facesNeeded == totalfFaces) {
//alert(facesNeeded);
//alert(totalfFaces);
leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
document.getElementById("rightside").appendChild(leftSideImages);
//alert("hi");
}
}
makeFaces();
function delFaces(side) {
while (side.firstChild) {
side.removeChild(side.firstChild);
}
}
theLeftSide.lastChild.onclick = function nextLevel(event) {
event.stopPropagation();
delFaces(theRightSide);
delFaces(theLeftSide);
totalfFaces = 0;
facesNeeded += 5;
//alert(facesNeeded);
//alert(totalfFaces);
makeFaces();
};
theBody.onclick = function gameOver() {
alert("Game Over!");
theBody.onclick = null;
theLeftSide.lastChild.onclick = null;
};
<!DOCTYPE html>
<html>
<head>
<style>
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#rightside {
left: 500px;
border-left: 1px solid black;
}
</style>
</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>
<script src="script3.js"></script>
</body>
</html>
You just need to move the onclick inside the makeFaces after the while, so its added everytime after it creates them all:-
var theLeftSide = document.getElementById("leftside");
var theRightSide = document.getElementById("rightside");
var facesNeeded = 5;
var totalfFaces = 0;
var theBody = document.getElementsByTagName("body")[0];
function makeFaces() {
while (facesNeeded != totalfFaces) {
smiley = document.createElement("img");
smiley.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
smiley.style.top = Math.random() * 401 + "px";
smiley.style.left = Math.random() * 401 + "px";
document.getElementById("leftside").appendChild(smiley);
totalfFaces++;
// alert(totalfFaces); used to debug
}
if (facesNeeded == totalfFaces) {
//alert(facesNeeded);
//alert(totalfFaces);
leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
document.getElementById("rightside").appendChild(leftSideImages);
//alert("hi");
}
theLeftSide.lastChild.onclick = function nextLevel(event) {
event.stopPropagation();
delFaces(theRightSide);
delFaces(theLeftSide);
totalfFaces = 0;
facesNeeded += 5;
//alert(facesNeeded);
//alert(totalfFaces);
makeFaces();
};
}
makeFaces();
function delFaces(side) {
while (side.firstChild) {
side.removeChild(side.firstChild);
}
}
theBody.onclick = function gameOver() {
alert("Game Over!");
theBody.onclick = null;
theLeftSide.lastChild.onclick = null;
};
<!DOCTYPE html>
<html>
<head>
<style>
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#rightside {
left: 500px;
border-left: 1px solid black;
}
</style>
</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>
<script src="script3.js"></script>
</body>
</html>

(HTML) JavaScript Collapsible Menu Error

http://jsfiddle.net/xNnQ5/
I am trying to use JavaScript (and HTML) to create a collapsible menu (c_menu) for my website. I would like it to be opened when the user clicks on the div menu_open, and to close when the user clicks menu_close. However, when I load the page, all that happens is the menu simply scrolls up, as if I have clicked menu_close, which I haven't. What should I do?
Code:
index.html (Only a snippet)
<style type = "text/css">
#c_menu {
position: absolute;
width: 435px;
height: 250px;
z-index: 2;
left: 6px;
top: 294px;
background-color: #0099CC;
margin: auto;
</style>
<div id="menu_open"><img src="images/open.jpg" width="200" height="88" /></div>
<input type="button" name="menu_close" id="menu_close" value="Close"/>
<div id="c_menu"></div>
<script type = "text/javascript" src = "menu.js"> </script>
menu.js (Full code)
document.getElementById("c_menu").style.height = "0px";
document.getElementById("menu_open").onclick = menu_view(true);
document.getElementById("menu_close").onclick = menu_view(false);
function menu_view(toggle)
{
if(toggle == true)
{
document.getElementById("c_menu").style.height = "0px";
changeheight(5, 250, 0);
}
if(toggle == false)
{
document.getElementById("c_menu").height = "250px";
changeheight(-5, 0, 250);
}
}
function changeheight(incr, maxheight, init)
{
setTimeout(function () {
var total = init;
total += incr;
var h = total + "px";
document.getElementById("c_menu").style.height = h;
if (total != maxheight) {
changeheight(incr, maxheight, total);
}
}, 5)
}
Try this:
document.getElementById("menu_open").onclick = function() {menu_view(true)};
document.getElementById("menu_close").onclick = function() {menu_view(false)};
When you define the function with a parenthesis ( ...onclick = menu_view(true) ), the function is called automatically.
When you have a function with no parameters, you can use it like you did, but without the parenthesis:
document.getElementById("menu_open").onclick = menu_view;
document.getElementById("menu_close").onclick = menu_view;

How to move/slide an image from left to right

I want to slide or move a image from left to right something like in
http://rajeevkumarsingh.wix.com/pramtechnology
The read pentagonal box that moves Ok!
I tried a bit but failed to do so.
I used the code as below:
<script type="text/javascript">
<!--
var imgObj = null;
var animate ;
function init(){
imgObj = document.getElementById('myImage');
imgObj.style.position= 'absolute';
imgObj.style.top = '240px';
imgObj.style.left = '-300px';
imgObj.style.visibility='hidden';
moveRight();
}
function moveRight(){
if (parseInt(imgObj.style.left)<=10)
{
imgObj.style.left = parseInt(imgObj.style.left) + 5 + 'px';
imgObj.style.visibility='visible';
animate = setTimeout(moveRight,20); // call moveRight in 20msec
//stopanimate = setTimeout(moveRight,20);
}
else
stop();
f();
}
function stop(){
clearTimeout(animate);
}
window.onload =init;
//-->
</script>
<img id="myImage" src="xyz.gif" style="margin-left:170px;" />
There some kind of resolution problem with Firefox and IE as well. How to solve them. Also I am not able to move the things so clearly. Is this possible or not? I want it to be with JavaScript and not Flash.
var animate, left=0, imgObj=null;
function init(){
imgObj = document.getElementById('myImage');
imgObj.style.position= 'absolute';
imgObj.style.top = '240px';
imgObj.style.left = '-300px';
imgObj.style.visibility='hidden';
moveRight();
}
function moveRight(){
left = parseInt(imgObj.style.left, 10);
if (10 >= left) {
imgObj.style.left = (left + 5) + 'px';
imgObj.style.visibility='visible';
animate = setTimeout(function(){moveRight();},20); // call moveRight in 20msec
//stopanimate = setTimeout(moveRight,20);
} else {
stop();
}
//f();
}
function stop(){
clearTimeout(animate);
}
window.onload = function() {init();};
Here is an example of moving an image to the right as well as fading in from a .js file instead of your index page directly:
----------My index.html page----------
<!DOCTYPE html>
<html>
<body>
<script src="myJava.js"></script>
<script language="javascript" type="text/javascript">
//In pixels
var amountToMoveTotal = 1000;
var amountToMovePerStep = 10;
//In milliseconds
var timeToWaitBeforeNextIncrement = 20;
var amountToFadeTotal = 1.0;
var amountToFadePerStep = 0.01;
</script>
<p>This one moves right on hover</p>
<img onmouseover="moveRight(this, amountToMoveTotal, amountToMovePerStep, timeToWaitBeforeNextIncrement)" src="http://www.w3schools.com/jsref/smiley.gif" style="left:0px;top:50px;position:absolute;opacity:1.0;">
<br><br>
<p>This one fades in on hover</p>
<img onmouseover="fadeIn(this, amountToFadeTotal, amountToFadePerStep, timeToWaitBeforeNextIncrement)" src="http://www.w3schools.com/jsref/smiley.gif" style="left:0px;top:150px;position:absolute;opacity:0.1;">
</body>
</html>
----------My myJava.js code----------
var animate;
var original = null;
function moveRight(imgObj, amountToMoveTotal, amountToMovePerStep, timeToWaitBeforeNextIncrement)
{
//Copy original image location
if (original === null){
original = parseInt(imgObj.style.left);
}
//Check if the image has moved the distance requested
//If the image has not moved requested distance continue moving.
if (parseInt(imgObj.style.left) < amountToMoveTotal) {
imgObj.style.left = (parseInt(imgObj.style.left) + amountToMovePerStep) + 'px';
animate = setTimeout(function(){moveRight(imgObj, amountToMoveTotal, amountToMovePerStep, timeToWaitBeforeNextIncrement);},timeToWaitBeforeNextIncrement);
}else {
imgObj.style.left = original;
original = null;
clearTimeout(animate);
}
}
function fadeIn(imgObj, amountToFadeTotal, amountToFadePerStep, timeToWaitBeforeNextIncrement)
{
//Copy original opacity
if (original === null){
original = parseFloat(imgObj.style.opacity);
}
//Check if the image has faded the amount requested
//If the image has not faded requested amount continue fading.
if (parseFloat(imgObj.style.opacity) < amountToFadeTotal) {
imgObj.style.opacity = (parseFloat(imgObj.style.opacity) + amountToFadePerStep);
animate = setTimeout(function(){fadeIn(imgObj, amountToFadeTotal, amountToFadePerStep, timeToWaitBeforeNextIncrement);},timeToWaitBeforeNextIncrement);
}else {
imgObj.style.opacity = original;
original = null;
clearTimeout(animate);
}
}
Use the jQuery library, is really easy to do what you need
http://api.jquery.com/animate/
Follow sample code of page : http://api.jquery.com/stop/
<!DOCTYPE html>
<html>
<head>
<style>div {
position: absolute;
background-color: #abc;
left: 0px;
top:30px;
width: 60px;
height: 60px;
margin: 5px;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<button id="go">Go</button>
<button id="stop">STOP!</button>
<button id="back">Back</button>
<div class="block"></div>
<script>
/* Start animation */
$("#go").click(function(){
$(".block").animate({left: '+=100px'}, 2000);
});
/* Stop animation when button is clicked */
$("#stop").click(function(){
$(".block").stop();
});
/* Start animation in the opposite direction */
$("#back").click(function(){
$(".block").animate({left: '-=100px'}, 2000);
});
</script>
</body>
</html>

Categories

Resources