Javascript - setInterval() still running after clearInterval() called - javascript

I'm making a game with Javascript. I have functions for moving left, right, gravity and down. The gravity function makes the player's location go to the bottom of the screen once it goes off the platform (div). When the gravity() function is called when you are moving right (OnButtonDownr()) it stops the move up from working. What I mean is that when I go right and off the platform and then try to go up it doesn't work but I can go up before I go off the platform. When I try to go up (and it doesn't work) it has a weird effect which looks like its position is being set to 0 but moving up at the same time. My code:
HTML (index.htm):
<html>
<head><link rel='stylesheet' href='style.css'></head>
<body>
<div id='level' class='level'>
<div class='start_platform' id='plat1'></div>
<div class='platform' style='
'></div>
</div>
<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='moveup' onmousedown="OnButtonDownu (this)" onmouseup="OnButtonUpu (this)">^</button>
<button id='moveright' onmousedown="OnButtonDownr (this)" onmouseup="OnButtonUpr (this)">--></button>
</div>
</body>
<script type='text/javascript' src='scripts/move.js'></script>
<script type='text/javascript' src='scripts/gravity.js'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</html>
JS (move.js):
//move left
var elem = document.getElementById("player");
function OnButtonDownl (button) {
var posl = parseInt(document.getElementById("player").style.left, 10) || 0;
window.idl = setInterval(framel, 5);
function framel() {
posl--;
elem.style.left = posl + 'px';
gravityCheck();
}}
function OnButtonUpl (button) {
clearInterval(idl);
}
//move right
var elem = document.getElementById("player");
function OnButtonDownr (button) {
var posr = parseInt(document.getElementById("player").style.left, 10) || 0;
window.idr = setInterval(framer, 5);
function framer() {
posr++;
elem.style.left = posr + 'px';
gravityCheck();
}}
function OnButtonUpr (button) {
clearInterval(idr);
}
//move up
var elem = document.getElementById("player");
function OnButtonDownu () {
var posu = parseInt(document.getElementById("player").style.bottom, 10) || 0;
window.idu = setInterval(frameu, 5);
elem.style.bottom = 0;
function frameu() {
gravity = false;
posu++;
elem.style.bottom = posu + 'px';
}}
function OnButtonUpu (button) {
clearInterval(idu);
}
JS (gravity.js):
var gravity = true;
function gravityCheck() {
var player = parseInt(document.getElementById("player").style.left, 10) || 0;
var plat1 = parseInt(document.getElementById("plat1").style.left, 10) || 0;
var width = player - plat1;
var elem = document.getElementById("player");
var pos = parseInt(document.getElementById("player").style.bottom, 10) || 0;
window.id = setInterval(frame, 5);
function frame() {
if(width > 100 && width < 164) {
if(gravity = true) {
pos--;
elem.style.bottom = pos + 'px';
if(elem.style.bottom = 0) {
clear();
}
}
}
}
function clear() {
clearInterval(id);
}}
How do I fix this. Thanks in advance.

You may not be clearing properly. Before setting interval clear any previously set one.
if(window.idl) clearInterval(window.idl);
window.idl = setInterval(framel, 5);

Related

Add scoreboard to "game"

I'm trying to make a small version of "duck hunt" I want to add a scoreboard when every time you hit the duck its +1 and when you miss its -1 but the score cant go lower than 0 (so not -1 for example) when you have tried 20 times the game stops and you will see your score so the hit and miss clicked times will show on the screen. How do I add this to my code so far I have got this:
var duck = document.getElementById('duck');
duck.style.position = 'relative';
var hit = 0;
var miss = 0
var count = 0;
var timing = setInterval(moveduck, 5000);
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
duck.addEventListener('click', moveduck);
function moveduck() {
var top = Math.floor(Math.random() * 750);
var left = Math.floor(Math.random() * 750);
var right = Math.floor(Math.random() * 750);
var bottom = Math.floor(Math.random() * 750);
var vertical = Math.floor(Math.random() * 750);
var horizontal = Math.floor(Math.random() * 750);
duck.style.top = top + 'px';
duck.style.left = left + 'px';
duck.style.right = right + 'px';
duck.style.bottom = bottom + 'px';
duck.style.vertical = vertical + 'px';
duck.style.horizontal = horizontal + 'px';
};
button1.onclick = succesfullhit;
function succesfullhit() {
hit++;
button1.innerHTML = hit;
}
button2.onclick = failedhit;
function failedhit() {
miss--;
button2.innerHTML = miss;
}
#duck { height:50px; }
<!DOCTYPE html>
<html lang="en">
<head>
<title>Duck hunt</title>
<link rel="stylesheet" type="text/css" href="Duckhunt.css">
</head>
<body>
<div class="container">
<input type="image" src="https://www.iconsdb.com/icons/preview/orange/duck-xxl.png" name="duck" id="duck" />
<button id="button1">Hit: </button>
<p></p>
<button id="button2">Miss: </button>
</div>
<script src="Duckhunt.js"></script>
</body>
</html>
I guess you want to do something like this :
i changed the hit and miss and i did only score.
i added event listener to the document, if you hit the duck score++ if not score--
and i display the score.
i added if statement, if score is === -1 game over.
if score === 20 win
Of course you need to do a bit work to make it perfect for your need, this is just for the beginning.
var duck = document.getElementById('duck');
duck.style.position = 'relative';
var score = 0
var timing = setInterval(moveduck, 5000);
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
function moveduck() {
var top = Math.floor(Math.random() * 750);
var left = Math.floor(Math.random() * 750);
var right = Math.floor(Math.random() * 750);
var bottom = Math.floor(Math.random() * 750);
var vertical = Math.floor(Math.random() * 750);
var horizontal = Math.floor(Math.random() * 750);
duck.style.top = top + 'px';
duck.style.left = left + 'px';
duck.style.right = right + 'px';
duck.style.bottom = bottom + 'px';
duck.style.vertical = vertical + 'px';
duck.style.horizontal = horizontal + 'px';
score++
};
document.addEventListener("click", function(e){
if(score === -1){
score = 0
document.getElementById('score').innerHTML = 'Game over'
console.log('game over')
}
if(score === 20){
document.getElementById('score').innerHTML = 'Win'
console.log('Win')
}
if (e.target.id === 'duck'){
moveduck()
document.getElementById('score').innerHTML = score
}else {
score--
document.getElementById('score').innerHTML = score
}
})
#duck { height:50px; }
<!DOCTYPE html>
<html lang="en">
<head>
<title>Duck hunt</title>
<link rel="stylesheet" type="text/css" href="Duckhunt.css">
</head>
<body>
<div id="scoreBoard">Score: <p id="score"></p></div>
<div class="container">
<input type="image" src="https://www.iconsdb.com/icons/preview/orange/duck-xxl.png" name="duck" id="duck" />
</div>
<script src="Duckhunt.js"></script>
</body>
</html>
Here is a start
var duck = document.getElementById('duck');
duck.style.position = 'relative';
var hit = 0;
var miss = 0
var count = 0;
var timing = setInterval(moveduck, 5000);
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
document.body.addEventListener('click', function(e) {
if (hit+miss >= 20) return
const tgt = e.target;
if (tgt.id ==="duck") succesfullhit()
else failedhit();
if (hit+miss === 20) clearInterval(timing)
else moveduck();
});
function moveduck() {
var top = Math.floor(Math.random() * 750);
var left = Math.floor(Math.random() * 750);
var right = Math.floor(Math.random() * 750);
var bottom = Math.floor(Math.random() * 750);
var vertical = Math.floor(Math.random() * 750);
var horizontal = Math.floor(Math.random() * 750);
duck.style.top = top + 'px';
duck.style.left = left + 'px';
duck.style.right = right + 'px';
duck.style.bottom = bottom + 'px';
duck.style.vertical = vertical + 'px';
duck.style.horizontal = horizontal + 'px';
};
function succesfullhit() {
hit++;
button1.innerHTML = hit;
}
function failedhit() {
miss++;
button2.innerHTML = -1*miss;
}
#duck { height:50px; }
<div class="container">
<input type="image" src="https://www.iconsdb.com/icons/preview/orange/duck-xxl.png" name="duck" id="duck" /><br/>
<button id="button1">Hit: </button>
<p></p>
<button id="button2">Miss: </button>
</div>

How can i create multiple audio players(each containing different song) without copying javascript functionality?

I dont know if my title is clear enough so ill try my best to sumerize.
I created audio player containing one song using audio tag. I made all functionality in javascript for player(progress bar, volume bar, play pause stop, time etc..) and now i want to repeat same plyer in column. I copied html and everything is ok but second player with different song is not triggering javascript even though all classes are the same.
My goal is to create something similar to soundcloud website where each audio has its own audio player but i dont want to copy javascript code for every audio. Is there a way to do this using same variables?
Code is huge btw :).
HTML:
<!-- AUDIO PLAYER -->
<div class="mainPlayerDiv">
<h1>Amelie Lens - Hypnotized</h1>
<div class="mainPlayer">
<div class="audioPlayerDiv">
<div class="playPauseBtn">
<div class="btnLine"></div>
<div class="btnLine"></div>
<div class="btnLine"></div>
</div>
<div class="stopBtnDiv">
<div class="stopBtn"></div>
</div>
<i class="fas fa-volume-down volumeDownIcon"></i>
<div class="mainVolumeDiv">
<div class="volumeBar" id="volumeBar">
<div id="volume"></div>
</div>
<span id="volPercentage"></span>
</div>
<div class="trackTime">
<span id="currTime"></span> /
<span id="duration"></span>
</div>
</div>
<a class="dlLink" href="/Track/Amelie Lens - Hypnotized.mp3" download="Amelie Lens - Hypnotized">
<button class="freeDownload">
<h5>mp3</h5>
<h3>Free Download</h3>
</button>
</a>
<button class="buyTrack">
<h3>Buy This Beat</h3>
</button>
</div>
<!--<canvas id="progress" width="500" height="10"></canvas>-->
<audio id="audio" class="track" src="/Track/Amelie Lens - Hypnotized.mp3" download></audio>
<div class="progressBarCont" id="progressBarCont">
<div class="progress" id="progress"></div>
</div>
</div>
Javascript:
// AUDIO PLAYER
var audioEl = document.querySelector('.track');
audioEl.addEventListener('loadedmetadata', function(){
var duration = audioEl.duration;
var currentTime = audioEl.currentTime;
document.getElementById("duration").innerHTML = convertElapsedTime(duration);
document.getElementById("currTime").innerHTML = convertElapsedTime(currentTime);
audioEl.volume = 0.31;
document.getElementById("volPercentage").innerHTML = 30 + " %";
});
// TIME UP
audioEl.addEventListener("timeupdate", function(){
var timeline = document.getElementById("currTime");
var s = parseInt(audioEl.currentTime % 60);
var m = parseInt((audioEl.currentTime / 60) % 60);
if (s < 10) {
timeline.innerHTML = m + ':0' +s;
} else {
timeline.innerHTML = m + ':' +s;
}
if (audioEl.ended) {
playPauseBtn.classList.remove('transform');
stopBtnDiv.classList.add('transform');
audioEl.currentTime = 0;
percent = 0;
progress.style.width = '0';
stopped = true;
clearInterval(interval);
clearInterval(interval2);
audioPlayerDiv.classList.remove('playAnimation');
audioPlayerDiv.classList.remove('playAnimation2');
}
}, false);
// OVERALL DURATION
function convertElapsedTime(inputSeconds) {
var seconds = Math.floor(inputSeconds % 60);
if (seconds < 10) {
seconds = "0" + seconds;
}
var minutes = Math.floor(inputSeconds / 60);
return minutes + ":" + seconds;
}
// PROGRESS BAR
var timer;
var percent = 0;
var audioEl = document.getElementById("audio");
audioEl.addEventListener("playing", function(_event) {
var duration = _event.target.duration;
advance(duration, audioEl);
});
audioEl.addEventListener("pause", function(_event) {
var progress = document.getElementById("progress");
clearTimeout(timer);
});
var advance = function(duration, element) {
var progress = document.getElementById("progress");
increment = 10/duration
percent = Math.min(increment * element.currentTime * 10, 100);
progress.style.width = percent+'%'
startTimer(duration, element);
}
var startTimer = function(duration, element){
if(percent < 100) {
timer = setTimeout(function (){advance(duration, element)}, 100);
}
}
// PROGRESS BAR SEEK
var progressBarCont = document.getElementById('progressBarCont');
var progress = document.getElementById("progress");
progressBarCont.addEventListener("mousedown", function(event){
var viewportset = progressBarCont.getBoundingClientRect();
var clickedPos = event.clientX - viewportset.left;
audioEl.currentTime = (clickedPos / event.target.offsetWidth) * audioEl.duration;
}, false);
// PROGRESS BAR END
/*
VOLUME SLIDER
*/
var volumeSlider = document.getElementById("volume");
var volumeBar = document.getElementById("volumeBar");
volumeBar.addEventListener('click', function(e){
var viewportOffset = volumeBar.getBoundingClientRect();
var cursorPosition;
cursorPosition = Math.floor(e.clientX - viewportOffset.left);
if(cursorPosition <= 9) {
audioEl.volume = '0.0' + cursorPosition;
document.getElementById("volPercentage").innerHTML = cursorPosition + " %";
volumeSlider.style.width = cursorPosition + "px";
} else if (cursorPosition === 100) {
audioEl.volume = 1;
document.getElementById("volPercentage").innerHTML = cursorPosition + " %";
volumeSlider.style.width = cursorPosition + "px";
} else {
audioEl.volume = '0.' + cursorPosition;
document.getElementById("volPercentage").innerHTML = cursorPosition + " %";
volumeSlider.style.width = cursorPosition + "px";
}
if(cursorPosition >= 50) {
volumeIconBtn.classList.remove('.fas');
volumeIconBtn.classList.remove('fa-volume-mute');
volumeIconBtn.classList.add('.fas');
volumeIconBtn.classList.add('fa-volume-up');
audioDownUp = 2;
} else {
volumeIconBtn.classList.remove('.fas');
volumeIconBtn.classList.remove('fa-volume-up');
}
if (cursorPosition <= 49) {
volumeIconBtn.classList.remove('.fas');
volumeIconBtn.classList.remove('fa-volume-mute');
volumeIconBtn.classList.add('.fas');
volumeIconBtn.classList.add('fa-volume-down');
audioDownUp = 1;
} else {
volumeIconBtn.classList.remove('.fas');
volumeIconBtn.classList.remove('fa-volume-down');
}
volPercentage.classList.add('showVolPercent');
setTimeout(function(){
volPercentage.classList.remove('showVolPercent');
}, 5000);
});
///////////////////// VOLUME SLIDER END
const playPauseBtn = document.querySelector('.playPauseBtn');
const stopBtnDiv = document.querySelector('.stopBtnDiv');
const stopBtn = document.querySelector('.stopBtn');
playPauseBtn.addEventListener('click', playPauseFunction);
stopBtnDiv.addEventListener('click', stopFunction);
let stopped = true;
var interval;
var interval2;
function playPauseFunction() {
if(audioEl.paused) {
playPauseBtn.classList.add('transform');
playPauseBtn.classList.add('transform2');
setTimeout(function(){
playPauseBtn.classList.remove('transform2');
}, 200);
audioEl.play();
audioEl2.play();
stopped = false;
let animation = 1;
interval = setInterval(function() {
if(animation === 1) {
audioPlayerDiv.classList.add('playAnimation');
animation = 0;
} else {
audioPlayerDiv.classList.remove('playAnimation');
animation = 1;
}
},16000);
let animation2 = 1;
interval2 = setInterval(function() {
if(animation2 === 1) {
audioPlayerDiv.classList.add('playAnimation2');
animation2 = 0;
} else {
audioPlayerDiv.classList.remove('playAnimation2');
animation2 = 1;
}
},32000);
} else {
playPauseBtn.classList.remove('transform');
playPauseBtn.classList.add('transform2');
setTimeout(function(){
playPauseBtn.classList.remove('transform2');
}, 200);
audioEl.pause();
stopped = false;
clearInterval(interval);
clearInterval(interval2);
audioPlayerDiv.classList.remove('playAnimation');
audioPlayerDiv.classList.remove('playAnimation2');
}
}
function stopFunction() {
if(!audioEl.paused) { // IF PLAYING
playPauseBtn.classList.remove('transform');
stopBtnDiv.classList.add('transform2');
stopBtnDiv.classList.add('transform');
setTimeout(function(){
stopBtnDiv.classList.remove('transform');
stopBtnDiv.classList.remove('transform2');
}, 200);
clearInterval(interval);
clearInterval(interval2);
audioPlayerDiv.classList.remove('playAnimation');
audioPlayerDiv.classList.remove('playAnimation2');
audioEl.currentTime = 0;
percent = 0;
progress.style.width = '0';
stopped = true;
audioEl.pause();
} else if (audioEl.paused && !stopped) {
stopBtnDiv.classList.add('transform');
stopBtnDiv.classList.add('transform2');
setTimeout(function(){
stopBtnDiv.classList.remove('transform');
stopBtnDiv.classList.remove('transform2');
}, 200);
clearInterval(interval);
clearInterval(interval2);
audioPlayerDiv.classList.remove('playAnimation');
audioPlayerDiv.classList.remove('playAnimation2');
audioEl.currentTime = 0;
percent = 0;
progress.style.width = '0';
stopped = true;
} else if (stopped){
audioEl.currentTime = 0;
percent = 0;
progress.style.width = '0';
stopped = true;
}
}
here's ss of players
Many thanks in advance.
You could use the Audio() constructor.
const player = (audiofile) => {
const newPlayer = new Audio(audiofile)
return newPlayer
}
https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement
Then create a new player by calling player('audio.wav')
ADDED:
Now that I can see your code, the other way to create many players dynamically is:
Create an array for your audio files:
const tracks = ['track1.wav', 'track2.wav']
Add a container for your players in your HTML
<div id="players"></div>
Add a function that creates a player and appends it to the container dynamically
const players = document.getElementById('players')
const player = (audiofile) => {
const newPlayer = document.createElement('audio')
audio.src = audiofile
// anything else you want to add
}
players.appendChild(newPlayer)
}
The audio() constructor and createElement(audio) both create new audio element, but audio() does not interact with the DOM.
Lastly, you would have to create a function that renders as many players as there are tracks.
Once you have rendered the players successfully, you should add an event listener for you controls so that the correct audio is played when user clicks on play etc.
https://developer.mozilla.org/en-US/docs/Web/API/Event/target

Have to move variable from left to right in Javascript. Professor has up and down as sample

new to javascript and taking a college course for game programming. Only using notepad. Now I have to move an object, in this case just the letter "o" from left to right. My professor provides code for the object going up and down the screen so I tried just to switch the "top" with "left" but it still wont move.
Prof sample:
<!-- Microsoft Edge, IE10/11, FireFox, Chrome -->
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var bH = document.documentElement.clientHeight; // return the browser’s height
function init() {
var m1 = document.getElementById("m1"); // m1 represent m1
var y = parseInt(m1.style.top); // y-coordinate of m1
if (y >= bH) {
y = 0;
} else {
y++;
}
m1.style.top = y + "px";
s1 = setTimeout("init()", 10); // wait 10 milliseconds and then call init
}
window.onload = function () {
init(); // onload event occurs right after a page is loaded
}
</script>
</head>
<body>
<span id="m1" style="position: absolute; top: 0px">o</span>
</body>
</html>
My attempt:
<!-- Chrome -->
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var bW = document.documentElement.clientWidth;
function init() {
var o = document.getElementById("o");
var x = parseInt(o.style.left);
if (x >= bW) {
x = 0;
} else {
x++;
}
o.style.left = x + "px";
s1 = setTimeout("init()", 10);
}
window.onload = function () {
init();
}
</script>
</head>
<body>
<span id="o" style="position: absolute; left: 0px">o</span>
</body>
</html>
Two three mistakes
using ; after window.onload = function(); is wrong
Don't add the function inside " " like s1=setTimeout("init()", 10); (it will work otherwise also, but i can't correctly figure out why not working in your case)
Solution: (js part only)
var bW = document.documentElement.clientWidth;
function init() {
var o = document.getElementById("o");
var x = parseInt(o.style.left);
if (x >= bW){
x = 0;
}
else{
x++;
}
o.style.left = x + "px";
s1=setTimeout(init(), 10);
}
window.onload = function(){
init();
}

onclick event not running, code sequence not correct

The code below runs as far as alert("click on extra image on the left") then it does nothing upon clicking on the extra image that is added to the left div. Upon clicking on the extra image (id="extraImage") I would like JS to change the color of the "extraImage" element to red. Also, I need to change the sequence in which the code is executed and run the alert("click on extra image on the left") AFTER pictures have been added. Any thoughts greatly appreciated.
<html>
<head> </head>
<body>
<div id="containerLeft">
</div>
<div id="containerRight">
</div>
<script>
var i = 1
var pocetSmilikov = prompt("enter number of smiley faces");
alert("i will add" + pocetSmilikov);
while (i <= pocetSmilikov)
{
insert();
i++;
}
insertExtraToLeft();
function insert() {
var imgDestination = document.getElementById("containerRight");
var imgAdded = document.createElement("img");
imgAdded.src = "smiley.png";
imgDestination.appendChild(imgAdded);
var left = Math.floor((Math.random() * 50) + 1) + "px";
var top = Math.floor((Math.random() * 50) + 1) + "px";
var imagestyle = imgAdded.style;
imagestyle.position = "relative";
imagestyle.top = top;
imagestyle.left = left;
var the_node = document.getElementById("containerRight").lastChild;
var the_clone = the_node.cloneNode(true);
document.getElementById("containerLeft").appendChild(the_clone);
}
function insertExtraToLeft() {
var imgDestinationExtra = document.getElementById("containerLeft");
var imgAddedExtra = document.createElement("img");
imgAddedExtra.src = "smiley.png";
imgAddedExtra.id = "extraImage"
imgDestinationExtra.appendChild(imgAddedExtra);
var left = Math.floor((Math.random() * 50) + 1) + "px";
var top = Math.floor((Math.random() * 50) + 1) + "px";
var imagestyle = imgAddedExtra.style;
imagestyle.position = "relative";
imagestyle.top = top;
imagestyle.left = left;
}
alert("click on extra image on the left");
extraImage.onclick = extraImgFound();
function extraImgFound() {
document.getElementById("extraImage").style.color = "red";
}
</script>
</body>
</html>
extraImage is not defined anywhere. Add imgAddedExtra.onclick = extraImgFound(); in your insertExtraToLeft() function.
Try:
function insertExtraToLeft()
{
var imgDestinationExtra = document.getElementById("containerLeft");
var imgAddedExtra = document.createElement("img");
imgAddedExtra.src = "smiley.png";
imgAddedExtra.id ="extraImage"
imgDestinationExtra.appendChild(imgAddedExtra);
imgAddedExtra.onclick = extraImgFound();
var left = Math.floor((Math.random() * 50) + 1)+"px";
var top = Math.floor((Math.random() * 50) + 1)+"px";
var imagestyle = imgAddedExtra.style;
imagestyle.position = "relative";
imagestyle.top = top;
imagestyle.left = left;
}

modifying a sliding javascript div

I got some code off the net to make a box slide in. However it slid in from the top left and I wanted it to slide in from the bottom. I changed the css position from top:-200px to bottom:-200px and changed the part of the code that alters the position from
{
popup.style.top = (currentTop + speed) + "px";
keepMoving = true;
}
to
{
popup.style.bottom = (currentTop + speed) + "px";
keepMoving = true;
}
now it doesn't work. I cannot see what variable I should be making. Here is the full code (which works if I change them back to 'top')
<html>
<head>
<title>Moving Pop Up Samplet</title>
<style>
#popup
{
height:200px;
width:200px;
border:1px solid #000;
background:#CC9900;
position:absolute;
bottom:-200px;
left:-200px;
}
</style>
<script>
var timer = null;
var speed = 3; //1 is slow
var endTop = 0;
var endLeft = 0;
//******************************************************
// Simple little function to get Elements as an object
//******************************************************
function getEl(id)
{
var el = document.getElementById(id);
return el;
}
//******************************************************
// Function to show Elements
//******************************************************
function showEl(id)
{
getEl(id).style.display ="";
}
//******************************************************
// Function to hide Elements
//******************************************************
function hideEl(id)
{
getEl(id).style.display ="none";
}
//******************************************************
// Function to move Element
//******************************************************
function moveEl(id)
{
var popup = getEl(id);
var currentTop = parseInt(popup.offsetTop);
var currentLeft = parseInt(popup.offsetLeft);
var keepMoving = false;
//Move
if (currentTop <= endTop)
{
popup.style.bottom = (currentTop + speed) + "px";
keepMoving = true;
}
if(currentLeft <= endLeft)
{
popup.style.left = (currentLeft + speed) + "px";
keepMoving = true;
}
if (keepMoving)
{
startMove(id);
}
else
{
endMove();
}
}
//******************************************************
// Function to start the move
//******************************************************
function startMove(id)
{
timer = setTimeout("moveEl('"+id+"')", 1);
}
//******************************************************
// Function to end the move
//******************************************************
function endMove()
{
clearTimeout(timer);
}
</script>
</head>
<body onload="startMove('popup');">
<!-- POP UP DIV -->
<div id="popup">
<center><span onclick="hideEl('popup');" style="cursor:pointer;"> Close</span></center>
</div>
<!--END POP UP DIV -->
<center><span onclick="startMove('popup');" style="cursor:pointer;"> Show Pop Up</span></center>
</body>
</html>
You'll just need to rejiggle your inequalities a bit.
Given that there's no offset bottom property in javascript, it'll be easier to still work with top values, even if you want to come in from the bottom.
function moveEl(id) {
var popup = getEl(id);
var currentTop = parseInt(popup.offsetTop);
var currentLeft = parseInt(popup.offsetLeft);
var keepMoving = false;
//Move
if (currentTop >= endTop) {
popup.style.top = (currentTop - speed) + "px";
keepMoving = true;
}
if (currentLeft <= endLeft) {
popup.style.left = (currentLeft + speed) + "px";
keepMoving = true;
}
if (keepMoving) {
startMove(id);
}
else {
endMove();
}
}
Here's a working jsFiddle.
If you think about the way the function is checking to see if it's finished yet, and adding on the speed variable each time, you should be able to step through the original version compared to this and see how the logic is working.
Instead writing something from scratch consider using jQuery's slideToggle method.

Categories

Resources