Failure to use accelerometer with HTML and JavaScript - javascript

I wonder why things go wrong is the application that I'm doing?
He did not start playing when I shake the phone.
I followed the instructions on this site, http://software.intel.com/pt-br/articles/create-handbell-using-html5-and-phonegap, but I do not quite understand how it works.
Here is the code:
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=320; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>BellShapes</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
function onLoad(){
// Aguardar o carregamento do Cordova
document.addEventListener("deviceready", onDeviceReady, false);
// inicialização
bellrightring = document.getElementById("bellrightring");
bellleftring = document.getElementById("bellleftring");
bellleft = document.getElementById("bellleft");
bellright = document.getElementById("bellright");
bellcenter = document.getElementById("bellcenter");
// inicialização da mídia
bellsound = new Media("/android_asset/www/resources/bell.mp3",
onRingSuccess(bellsound), onRingError);
bellend = new Media("/android_asset/www/resources/bell-end.mp3",
onRingSuccess(bellend), onRingError);
}
function sign(val, delta) {
if (typeof delta == undefined) delta=0
if (val > 0 && Math.abs(val)-delta > 0) return 1;
else if (val<0 && Math.abs(val)-delta > 0) return -1;
else return 0;
}
function isShaking(last, current, threshold) {
var deltaX = Math.abs(last.x - current.x),
deltaY = Math.abs(last.y - current.y),
deltaZ = Math.abs(last.z - current.z);
return ((deltaX > threshold && deltaY > threshold) ||
(deltaX > threshold && deltaZ > threshold) ||
(deltaY > threshold && deltaZ > threshold) || deltaX > threshold);
}
accelID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
function onSuccess(acceleration) {
var x = acceleration.x;
var y = acceleration.y;
var z = acceleration.z;
var t = false;
if (previous){
if (isShaking(previous, acceleration, 10)){
moveBell(sign(x));
bellsound.play();
accelerated = true;
}
else {
stopBell(acceleration);
if (accelerated == true){
bellend.play();
}
accelerated = false;
}
}
previous = acceleration;
}
</script>
</head>
<body id="onLoad">
<div id="handbell">
<div id="bellcenter" class="position"></div>
<div id="bellright" class="position"></div>
<div id="bellleft" class="position"></div>
<div id="bellrightring" class="ring"></div>
<div id="bellleftring" class="ring"></div>
</div>
</body>
</html>
I do not know much about javascript, so I would appreciate if you could explain in a simpler way.

In your body tag you have written
<body id="onLoad">
This should be
<body onLoad="onLoad()">
You need to have the function onLoad called when the page loads.
Alternatively, you could remove the id and forget about the onload in the body tag.
Then add this one line to the Javascript.
window.addEventListener("load", onLoad);

Related

My JavaScript slideshow goes forward an image and then back after selecting previous

I am creating a JavaScript slideshow. It works for the most part. However, when toggling back after moving forward many images it goes forward one image, and then will go back. It will also do this when going forward an image aver toggling back for a while. I do not know if this post makes much sense as it is a difficult question to phrase.
const nextBtn = document.querySelector("next");
const previousBtn = document.querySelector("previous");
const image = document.getElementById("slideShow");
let imageNumber = 0;
console.log(image.src, imageNumber);
const slideForward = function () {
image.src = `slide-${imageNumber++}.PNG`;
console.log(image.src, imageNumber);
if (imageNumber > slideArray.length - 1) {
imageNumber = 1;
}
};
const slideBack = function () {
image.src = `slide-${imageNumber--}.PNG`;
console.log(image.src, imageNumber);
if (imageNumber < 0) {
imageNumber = slideArray.length - 1;
}
};
document.addEventListener("keydown", function (q) {
if (q.key === "ArrowLeft") {
slideBack();
}
});
document.addEventListener("keydown", function (q) {
if (q.key === "ArrowRight") {
slideForward();
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="preconnect" href="https://fonts.gstatic.com" />
<link
href="https://fonts.googleapis.com/css2?family=Days+One&family=Roboto:ital,wght#0,400;1,900&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="style.css" />
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<body id="picturesStyle" >
<nav class="topnav">
<ul>
<li>Home</li>
<li>Books</li>
<li>Movies</li>
<li>Videos</li>
<li>Pictures</li>
</ul>
</nav>
<img width="600" id="slideShow" src="PleaseWork.png" alt="">
<button class="next" onclick="slideForward()">Next</button>
<button class="previous" onclick="slideBack()">Previous</button>
</main>
<title>SlideShow</title>
<script src="script.js"></script>
</body>
</html>
If I understand you correctly I think the reason you are experiencing the issue caused by the lines
image.src = `slide-${imageNumber++}.PNG`;
image.src = `slide-${imageNumber--}.PNG`;
and if checks and the starting index of the array.
I would do like this
const slideForward = function () {
if (++imageNumber >= slideArray.length) { //Increase the value first and check it if it is out of range
imageNumber = 0; //indexes don't start from 1. They start from 0
}
image.src = `slide-${imageNumber}.PNG`;
console.log(image.src, imageNumber);
};
Same logic applies for slideBack function
const slideBack = function () {
if (--imageNumber <= 0) { //Decrease the value first and check it if it is out of range
imageNumber = slideArray.length - 1;
}
image.src = `slide-${imageNumber}.PNG`;
console.log(image.src, imageNumber);
};
I hope that covers your question
Please try this and give feedback how it goes:
const slideForward = function () {
if (imageNumber > slideArray.length - 1) {
imageNumber = -1;
}
imageNumber++;
image.src = `slide-${imageNumber}.PNG`;
console.log(image.src, imageNumber);
};
const slideBack = function () {
if (imageNumber < 0) {
imageNumber = slideArray.length;
}
imageNumber--;
image.src = `slide-${imageNumber}.PNG`;
console.log(image.src, imageNumber);
};
Don't increment or decrement the counter unless it's in the range of your slide array and only add one "keydown" event.
const nextBtn = document.querySelector("next");
const previousBtn = document.querySelector("previous");
const image = document.getElementById("slideShow");
let imageNumber = 0;
console.log(image.src, imageNumber);
const slideForward = function () {
if(imageNumber >= 0 && imageNumber < slideArray.length - 1){
imageNumber++;
image.src = `slide-${imageNumber}.PNG`;
}
console.log(image.src, imageNumber);
};
const slideBack = function () {
if(imageNumber > 0 && imageNumber <= slideArray.length - 1){
imageNumber--;
image.src = `slide-${imageNumber}.PNG`;
}
console.log(image.src, imageNumber);
};
document.addEventListener("keydown", function (q) {
if (q.key === "ArrowLeft") {
slideBack();
}
if (q.key === "ArrowRight") {
slideForward();
}
});

How can I reset time in a simple game?

I've tried make simple clicking game (if time count is higher than 5, the game is over, but you can reset time if you click generated element).
Unfortunately time is still counting. How can I fix this?
Why do I get this error?
Uncaught TypeError: Cannot set property 'textContent' of null
at js.js:8
at js.js:49
(function() {
const startGame = document.querySelector('button')
let time = 0;
let roll = true;
let h2 = document.querySelector('h2')
h2.textContent = time;
const timeFlow = () => {
time++
}
const resetTime = () => {
time = 0;
console.log(time)
}
const rollBall = () => {
if (roll == true) {
let divCreator = document.createElement('div')
document.body.appendChild(divCreator)
divCreator.classList.add('square')
divCreator.style.backgroundColor = 'red'
divCreator.style.top = Math.floor(Math.random() * 99) + '%'
divCreator.style.left = Math.floor(Math.random() * 99) + '%'
divCreator.addEventListener('click', letsPlay)
divCreator.addEventListener('click', resetTime)
setInterval(timeFlow, 1000)
} else if (roll == false) {
roll = true;
}
}
const letsPlay = (e) => {
let start = document.body.removeChild(e.target)
roll = false;
if (time >= 5) {
alert('U lost')
} else {
rollBall()
}
}
startGame.addEventListener('click', rollBall)
})();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button>Generate</button>
<script src='js.js'></script>
<h2>Time</h2>
</body>
</html>
You can use the load event instead of an IIFE before the elements exist.
Also your div needs dimensions
Also I assume you want the time in the H2?
Also you need position absolute to move the div
Lastly I clear the interval before a new one
window.addEventListener("load", function() {
const startGame = document.querySelector('button')
const h2 = document.querySelector('h2')
let tId;
let time = 0;
let roll = true;
h2.textContent = time;
const timeFlow = () => {
time++
h2.textContent = time;
}
const resetTime = () => {
time = 0;
}
const rollBall = () => {
if (roll == true) {
let divCreator = document.createElement('div')
document.body.appendChild(divCreator)
divCreator.classList.add('square');
divCreator.style.height = '50px'
divCreator.style.width = '50px'
divCreator.style.backgroundColor = 'red'
divCreator.style.position = 'absolute'
divCreator.style.top = Math.floor(Math.random() * 99) + '%'
divCreator.style.left = Math.floor(Math.random() * 99) + '%'
divCreator.addEventListener('click', letsPlay)
divCreator.addEventListener('click', resetTime)
clearInterval(tId); // remove any running interval
tId = setInterval(timeFlow, 1000)
}
roll = !roll;
}
const letsPlay = (e) => {
let start = document.body.removeChild(e.target)
roll = false;
if (time >= 5) {
alert('U lost')
} else {
roll = true; // right?
rollBall()
}
}
startGame.addEventListener('click', rollBall)
})
body {
height: 100%;
background-color: yellow;
}
<button>Generate</button>
<h2>Time</h2>
Your HTML code is in the wrong order: the <h2> element and the <script> element should be switched.
You should change it like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button>Generate</button>
<h2>Time</h2>
<script src='js.js'></script>
</body>
</html>

In a jsf web application, a Javascript based session timer works on Chrome but not on IE

In a jsf web application based on Seam and Richfaces, I ran into a problem concerning different browsers. The code (and every variation I tried) works flawless in Chrome, but not in Internet Explorer (I am testing version 11).
The code is supposed to start and display a session-timeout countdown in the header. In the beginning of the template file, the timeout is retrieved from the application preferences and stored in a hidden field. The countdown timer is reset whenever a new page is loaded, or when an AJAX request is triggered (resetInactivityTimer()).
I am having 2 problems in IE:
It seems that the window.onloadfunction is not triggered on IE. The counter starts working fine when triggered manually in the console.
When the counter is started manually, an error occurs when an AJAX request is triggered.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Title</title>
<link rel="shortcut icon" type="image/x-icon" href="#{facesContext.externalContext.requestContextPath}/img/favicon.ico" />
<a:loadStyle src="/stylesheet/theme.css" />
<ui:insert name="head" />
</head>
<body>
<h:inputHidden id="originalTimeoutId" value="#{preferencesManager.getPreferenceValue(Preference.HTTP_SESSION_TIMEOUT)}"/>
<a:loadScript src="/scripts/script.js"/>
<a:region id="status_zone">
<a:status for="status_zone" forceId="false" id="ajaxStatus" onstart="resetInactivityTimer()">
<f:facet name="start">
<h:panelGroup>
<div style="position: absolute; left: 50%; top: 50%; text-align:center; width: 100%; margin-left: -50%;z-index: 10001;" >
<h:graphicImage value="/img/wait.gif"/>
</div>
<rich:spacer width="95%" height="95%" style="position: absolute; z-index: 10000; cusor: wait;" />
</h:panelGroup>
</f:facet>
</a:status>
<div class="main">
<ui:include src="/layout/header.xhtml" />
<ui:include src="/layout/menu.xhtml" />
<div style="margin-top: 10px;">
<ui:insert name="body" />
</div>
<ui:include src="/layout/footer.xhtml" />
</div>
</a:region>
<script type="text/javascript">
window.onload = initCountdown();
</script>
</body>
</html>
The countdown timer is displayed in the top right corner in the Header file "header.xhtml", which is loaded in the template, and therefore contained on every page:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:s="http://jboss.com/products/seam/taglib"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<div class="header">
<s:graphicImage value="#{preferencesManager.getPreferenceByteContent(Preference.LOGO)}" styleClass="logo"/>
<h:panelGrid width="92%" columns="3" columnClasses="headerCol2,headerCol3,headerCol4">
<h:outputText styleClass="titel"
value="#{cM.getStringProp('de.gai_netconsult.kodaba.text.title')}"/>
<span class="timer">Automatischer Logout in: </span>
<h:outputText id="counter" styleClass="timer"></h:outputText>
</h:panelGrid>
</div>
The time is placed at the id="counter" position.
This is the Javascript code: "script.js"
var hiddenField;
var timeoutInSeconds;
var originalTimeout;
var originalCounter;
var initialized = false;
function initCountdown(){
// quit if this function has already been called
if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
// do stuff
startCountdown();
}
function getHiddenField() {
if (hiddenField != null) {
timeoutInSeconds = parseInt(hiddenField.value) * 60;
return timeoutInSeconds;
}
try {
hiddenField = document.getElementById('originalTimeoutId');
} catch (e) {
timeoutInSeconds = 0;
}
return timeoutInSeconds;
}
function getOriginalCounter(){
return document.getElementById('counter');
}
function resetInactivityTimer() {
if (initialized) {
console.log("resetInactivityTimer - initialized: " + initialized);
stopCountdown();
countdown(timeoutInSeconds, 'counter');
}
}
function startCountdown () {
timeoutInSeconds = getHiddenField();
if(timeoutInSeconds == 0) return;
originalCounter = getOriginalCounter();
if(timeoutInSeconds == null || originalCounter == null) {
setTimeout(function(){
startCountdown()}, 1000);
}
if(timeoutInSeconds != null && originalCounter != null){
initialized = true;
originalTimeout = timeoutInSeconds;
countdown(originalTimeout, 'counter');
}
}
function stopCountdown() {
var element = document.getElementById('counter');
clearTimeout(element.timerId);
}
function leadingzero(number) {
return (number < 10) ? '0' + number : number;
}
function countdown(seconds, target) {
var element = document.getElementById(target);
element.seconds = seconds;
calculateAndShow('counter');
}
function calculateAndShow(target) {
var element = document.getElementById('counter');
if (element.seconds >= 0) {
element.timerId = window.setTimeout(calculateAndShow,1000,target);
var h = Math.floor(element.seconds / 3600);
var m = Math.floor((element.seconds % 3600) / 60);
var s = element.seconds % 60;
element.innerHTML=
leadingzero(h) + ':' +
leadingzero(m) + ':' +
leadingzero(s);
element.seconds--;
} else {
completed(target);
return false;
}
}
function completed(target) {
var element = document.getElementById(target);
element.innerHTML = "<strong>Finished!<\/strong>";
}
Some things I tried is replacing
<script type="text/javascript">
window.onload = initCountdown();
</script>
with
<script type="text/javascript">
if (window.attachEvent) {window.attachEvent('onload', initCountdown());}
else if (window.addEventListener) {window.addEventListener('load', initCountdown(), false);}
else {document.addEventListener('load', initCountdown(), false);}
</script>
This leads to a "Typeconflict".
or with:
<rich:jQuery name="jcountdown" query="initCountdown()" timing="onload"/>
None of this helps.
I was able to get my timer to work in the end and I will post my solution here:
Problem 1:
<script type="text/javascript">
jQuery(document).ready(function(){
startCountdown();
});
</script>
instead of window.onload = startCountdown(); solves the problem.
Important: when using any console.log() statements, the function will only be executed when the developer console is opened! (F12).
Problem 2: (AJAX)
Richfaces version 3.3 is simply not compatible with any Internet Explorer Version above IE8.
It is important to apply a patch. This site describes the process in detail.
I also had to make many changes to the Javascript code. I am sure this could be much more elegantly written, but I confess I don't really know much Javascript at all... I'm posting my code anyway, in case somebody may find it useful:
var hiddenField;
var timeoutInSeconds;
var originalTimeout;
var originalCounter;
function getHiddenField() {
if (hiddenField != null) {
timeoutInSeconds = parseInt(hiddenField.value) * 60 -1;
timeoutInSeconds;
return timeoutInSeconds;
}
try {
hiddenField = document.getElementById('originalTimeoutId');
} catch (e) {
timeoutInSeconds = 0;
}
return timeoutInSeconds;
}
function getOriginalCounter(){
return document.getElementById('counter');
}
function startCountdown () {
timeoutInSeconds = getHiddenField();
if(timeoutInSeconds == 0) return;
originalCounter = getOriginalCounter();
if(timeoutInSeconds == null || originalCounter == null) {
setTimeout(function(){
startCountdown()}, 1000);
}
if(timeoutInSeconds != null && originalCounter != null){
originalTimeout = timeoutInSeconds;
countdown(originalTimeout, 'counter');
}
}
function countdown(seconds, target) {
var element = document.getElementById(target);
element.seconds = seconds;
calculateAndShow('counter');
}
function resetCountdown(){
var element = document.getElementById('counter');
element.seconds = timeoutInSeconds;
updateDisplay(element);
}
function calculateAndShow() {
var element = document.getElementById('counter');
if (element.seconds > 0) {
element.timerId = window.setTimeout(calculateAndShow,1000,'counter');
updateDisplay(element);
element.seconds--;
} else {
completed();
return false;
}
}
function updateDisplay(element){
var h = Math.floor(element.seconds / 3600);
var m = Math.floor((element.seconds % 3600) / 60);
var s = element.seconds % 60;
element.innerHTML =
leadingzero(h) + ':' +
leadingzero(m) + ':' +
leadingzero(s);
}
function leadingzero(number) {
return (number < 10) ? '0' + number : number;
}
function completed() {
var element = document.getElementById('counter');
element.innerHTML = "<strong>Beendet!<\/strong>";
logoutCallBackToServer();
}
Somewhere in one of your xhtml files (template, Header, menu, whatever) you also need to add this line:
<a4j:jsFunction name="logoutCallBackToServer" immediate="true" action="#{identity.logout}" />
This will ensure that the user is actually logged out precisely when the countdown reaches zero, just in case this does not 100% match the actual session time out.

slideshow with page numbers javascript

I have created slideshow. I want to add some description with page numbers.
I was trying to add function sliderText() to get result - "Image 1 of 7" etc.
I don't know what is wrong here. Can somebody give me some hints?
Thank you in advance,
Megi
var img_index = 0;
var imgs = [
"assets/1.jpg",
"assets/2.jpg",
"assets/3.jpg",
"assets/4.jpg",
"assets/5.jpg",
"assets/6.jpg",
"assets/7.jpg"
];
function findNextImage(isPrev) {
switch (true) {
case !!(isPrev && imgs[img_index + 1]):
img_index += 1
return imgs[img_index]
case !!imgs[img_index + 1]:
img_index += 1
return imgs[img_index]
default:
img_index = 0
return imgs[img_index]
}
sliderText()
}
function checkKey(event) {
if (event.keyCode == '39') {
document.getElementById("images").src = findNextImage();
} else if (event.keyCode == '37') {
document.getElementById("images").src = findNextImage(true);
}
}
document.onkeydown = checkKey;
function sliderText() {
var text = document.getElementsByClassName("slideshow_text");
var imageNumber = img_index + 1;
text.innerHTML = "image " + imageNumber + " of " + imgs.length;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>test</title>
</head>
<h1 class="slideshow_text">Image 1 of 7</h1>
<img id="images" src="assets/1.jpg" />
<body>
</body>
<script src="test.js"></script>
</html>
Some modifications to improve code quality
I removed findNextImage which was not a pure function and introduced findNextImageIndex instead: findNextImageIndex neither accesses nor modifies any external variables and is thus easier to read. sliderText takes imgIndex as an argument so that you can easily see what parameters it needs to set the text.
Further suggestions
Consider moving the pre-set values Image 1 of 7 and "assets/1.jpg" from HTML to JavaScript as well. Initialize the slider with "assets/1.jpg" taken from the array and call sliderText(state.imgIndex); once initially.
Please notice that I moved the slide show HTML inside the <body> to make it valid HTML.
Modified code
var state = {
imgIndex: 0
};
var imgs = [
"assets/1.jpg",
"assets/2.jpg",
"assets/3.jpg",
"assets/4.jpg",
"assets/5.jpg",
"assets/6.jpg",
"assets/7.jpg"
];
function findNextImageIndex(imgIndex, isPrev) {
if(isPrev) {
if(imgIndex <= 0) {
return imgs.length - 1;
} else {
return imgIndex - 1;
}
} else {
if(imgIndex >= imgs.length - 1) {
return 0;
} else {
return imgIndex + 1;
}
}
}
function sliderText(imgIndex) {
var text = document.getElementsByClassName("slideshow_text")[0];
var imageNumber = imgIndex + 1;
text.innerHTML = "image " + imageNumber + " of " + imgs.length;
}
function goToNextImage(isPrev) {
state.imgIndex = findNextImageIndex(state.imgIndex, isPrev);
document.getElementById("images").src = imgs[state.imgIndex];
sliderText(state.imgIndex);
}
function checkKey(event) {
switch(event.keyCode) {
case 37: goToNextImage(true); break;
case 39: goToNextImage(false); break;
}
}
document.onkeydown = checkKey;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>test</title>
</head>
<body>
<h1 class="slideshow_text">Image 1 of 7</h1>
<img id="images" src="assets/1.jpg" />
<script src="test.js"></script>
</body>
</html>

Repeating Javascript Animations?

I'm trying to make a div go up, down, up again, down again, etc. until you click on it. This is what I've got:
<!DOCTYPE html>
<html>
<head>
<title>Fun with animations dude</title>
<link rel="stylesheet" href="animation.css"/>
</head>
<body>
<div id="moving">
</div>
<script type="text/javascript">
var moving = document.getElementById("moving");
var mMargin = moving.style.marginTop | 0;
var moving = false;
moving.onclick = start;
function start() {
if (moving == false) {
moving = true;
move();
window.alert("Start!");
}
else {
moving = false;
window.alert("Aww...");
}
}
function move() {
if (moving) {
if (mMargin < 700) {
mMargin += 10;
moving.style.marginTop = mMargin + "px";
setTimeout(move, 20);
}
else {
mMargin -= 10;
moving.style.marginTop = mMargin + "px";
setTimeout(move, 20);
}
}
}
</script>
</body>
</html>
I was actually quite proud of myself for a while, until it didn't work... As you can see, I made an attempt at troubleshooting by adding those alert boxes. Neither of them were triggered, so right now it's a problem with the initial stuff, although there may be other errors as well. No errors in the console. Advice?
Hippydog's answer got me past the first part. I then realized I had to add another variable to keep the div from spazing out at the bottom of the first run. I just wanted to post what worked for anyone else looking at this for reference:
<!DOCTYPE html>
<html>
<head>
<title>Fun with animations dude</title>
<link rel="stylesheet" href="animation.css"/>
</head>
<body>
<div id="moving">
</div>
<script type="text/javascript">
var moving = document.getElementById("moving");
var mMargin = moving.style.marginTop | 0;
var isMoving = false;
var movingDown = true;
moving.onclick = start;
function start() {
if (isMoving == false) {
isMoving = true;
move();
}
else {
isMoving = false;
}
}
function move() {
if (isMoving) {
if (movingDown) {
mMargin += 10;
moving.style.marginTop = mMargin + "px";
if (mMargin >= 1000) {
movingDown = false;
}
setTimeout(move, 20);
}
else {
mMargin -= 10;
moving.style.marginTop = mMargin + "px";
if (mMargin <= 0) {
movingDown = true;
}
setTimeout(move, 20);
}
}
}
</script>
</body>
</html>
If any more experienced coders find some unforseen problem with this script, feel free to let me know.
The first and third local variables are both called moving. Renaming the second to isMoving (and updating any mentions of this variable) causes the alerts to show as expected.

Categories