How to activate an interval when a certain position is reached? - javascript

The problem is that It calls the var intervalLeft and intervaRight at the same time. When it is moving right I want the intervalLeft not to work & vice versa.
When It reaches startPosition 100 it activates the intervalLeft and when it reaches startPosition 0 it activates intervalRight infinite.
<div id="moveAnimation" class="block"></div>
</div>
<script>
var elem = document.getElementById("moveAnimation");
elem.addEventListener("click", movingImage);
function movingImage() {
var startPosition = 0;
var intervalRight = setInterval(frameRight, 10);
var intervalLeft = setInterval(frameLeft, 10);
function frameRight() {
if (startPosition >= 100) {
clearInterval(intervalRight);
frameLeft();
} else {
startPosition += 0.5;
document.getElementById("moveAnimation").style.left = startPosition + "%";
}
}
function frameLeft() {
if (startPosition <= 0) {
clearInterval(intervalRight);
frameRight();
} else {
startPosition -= 2;
document.getElementById("moveAnimation").style.right = startPosition + "%";
}
}
}
</script>
This is the exercise:
Below this, you have a div that needs to move left to right using JS for the motion. Make it reach the end in 2 seconds, then return in 5s. Repeat that forever.

Have updated your code. Use below
<div id="moveAnimation" class="block"></div>
</div>
<script>
var elem = document.getElementById("moveAnimation");
elem.addEventListener("click", movingImage);
function movingImage() {
var startPosition = 0;
var intervalRight = setInterval(frameRight, 10);
var rightTimer = true;
var leftTimer = false;
var intervalLeft;
function frameRight() {
if(!rightTimer){
rightTimer = true;
intervalRight = setInterval(frameRight,10)
return;
}
if (startPosition >= 100) {
rightTimer = false;
clearInterval(intervalRight);
frameLeft();
} else {
startPosition += 0.5;
document.getElementById("moveAnimation").style.left = startPosition + "%";
}
}
function frameLeft() {
if(!leftTimer){
leftTimer = true;
intervalLeft = setInterval(frameLeft,10)
return;
}
if (startPosition <= 0) {
leftTimer = false;
clearInterval(intervalLeft);
frameRight();
} else {
startPosition -= 2;
document.getElementById("moveAnimation").style.left = startPosition + "%";
}
}
}
</script>

After testing some more i've found the answer with fewer lines of code.
var elem = document.getElementById("moveAnimation");
elem.addEventListener("click", movingImage);
function movingImage() {
var startPosition = 0;
var intervalRight = setInterval(frameRight, 10); //1
function frameRight() {
if (startPosition >= 100) {
clearInterval(intervalRight);
intervalLeft = setInterval(frameLeft, 10);
} else {
startPosition += 0.5;
document.getElementById("moveAnimation").style.left = startPosition + "%";
}
}
function frameLeft() {
if (startPosition <= 0) {
clearInterval(intervalLeft);
intervalRight = setInterval(frameRight, 10);
} else {
startPosition -= 0.2;
document.getElementById("moveAnimation").style.left = startPosition + "%";
}
}
}
</script>
this works how it Should. In the original code I posted the clearInterval was not linked to an actual intervalID

Related

I do not know how to limit the time in between calling my function

//let screenWidth = window.screen.width;
//let screenHeight = window.screen.height;
let screenWidth = 800;
let screenHeight = 600;
let assets = {};
let frames = 60;
let score = 0;
let lives = 3;
let player;
// let enemie;
//let enemies;
let bullet;
//let bullets;
let powerup = 0;
let gameOver = true;
function drawScoreBoard() {
textSize(20);
fill('white');
text(`Score: ${score} / Lives: ${lives}`, 20, 40);
}
function preload() {
assets.player = loadImage('assets/Player.png');
assets.enemie = loadImage('assets/Enemie.png');
assets.bulletRight = loadImage('assets/Bullet_Right.png');
assets.bulletLeft = loadImage('assets/Bullet_Left.png');
assets.bulletUp = loadImage('assets/Bullet_Up.png');
assets.bulletDown = loadImage('assets/Bullet_Down.png');
}
function setup() {
bullets = createGroup();
enemies = createGroup();
assets.player.resize(30, 30);
assets.enemie.resize(30, 30);
assets.bulletRight.resize(30, 30);
assets.bulletLeft.resize(30, 30);
assets.bulletUp.resize(30, 30);
assets.bulletDown.resize(30, 30);
createCanvas(screenWidth, screenHeight);
}
function createBullet(){
let numList = [0, 90, 180, 270, 360];
let bulletDirection = [assets.bulletLeft, assets.bulletUp, assets.bulletRight, assets.bulletDown];
let randomdirection = numList[Math.floor(Math.random() * numList.length)];
let bullet = createSprite(bulletDirection[(Math.round(player.getDirection()/90))]);
enemie.centerX = random(0, screenWidth);
enemie.setSpeed(random(1,10));
enemie.setDirection(randomdirection);
enemie.setCollider("circle");
bullets.add(bullet);
}
function createPlayer(){
player = createSprite(assets.player);
player.bottom = screenHeight - 20;
player.centerX = screenWidth / 2;
}
function shoot(amountofbulletstobeshot) {
let bulletDirection = [assets.bulletLeft, assets.bulletUp, assets.bulletRight, assets.bulletDown];
let bullet = createSprite(bulletDirection[Math.abs(((Math.round(player.getDirection()/90))))]);
bullets.add(bullet);
// bullet.direction = player.direction;
bullet.centerX = player.centerX;
bullet.centerY = player.centerY;
bullet.setVelocity(11, player.getDirection());
// console.log('The players current direction right now is: ' + player.getDirection());
}
function shooting() {
if (keyIsDown(KEY.SPACE)) {
if (powerup === 1) {
shoot(3);
}
else {
shoot(1);
}
}
if (bullet) {
if (bullet.centerX[1] === screenWidth) {
bullets.remove(bullet);
}
}
}
function updateplayer() {
//movement
if (keyIsDown) {
if (keyIsDown(KEY.RIGHT_ARROW)) {
player.setVelocity(6, 0);
}
if (keyIsDown(KEY.LEFT_ARROW)) {
player.setVelocity(6, 180);
}
if (keyIsDown(KEY.UP_ARROW)) {
player.setVelocity(6, 270);
}
if (keyIsDown(KEY.DOWN_ARROW)) {
player.setVelocity(6, 90);
}
}
//dont go offscreen
if (player.left < 0) {
player.left = 0;
}
if (player.right > screenWidth) {
player.right = screenWidth;
}
if (player.top < 0) {
player.top = 0;
}
if (player.bottom > screenHeight) {
player.bottom = screenHeight;
}
enemies.overlap(player, HandlePlayerEnemieCollision);
//end up updateplayer
}
function updateEnemie() {
if (frameCount % 1 === 0) {
let directions = ["LEFT", "RIGHT", "UP", "DOWN"];
let direction = random(directions);
if (direction === "LEFT" && enemie.left > 0) {
enemie.centerX -= 5;
}
if (direction === "RIGHT" && enemie.right < screenWidth) {
enemie.centerX += 5;
}
if (direction === "UP" && enemie.top > 0) {
enemie.centerY -= 5;
}
if (direction === "DOWN" && enemie.bottom < screenHeight) {
enemie.centerY += 5;
}
}
}
function createEnemie() {
let directions = [270, 180, 0, 90];
direction = directions[(Math.floor(Math.random() * 5))];
enemies.overlap(bullets, HandleEnemieBulletCollision);
if (frameCount % 60 === 0) {
enemie = createSprite(assets.enemie);
enemie.centerX = Math.floor(Math.random() * 300) + 100;
enemie.centerY = Math.floor(Math.random() * 300) + 100;
enemie.setVelocity(Math.floor(Math.random() * 5) + 1, direction);
enemies.add(enemie);
}
}
function HandleEnemieEdgeCollision(enemie, edge) {
if (enemie.centerY === screenWidth) {
enemie.remove();
}
}
function HandleEnemieBulletCollision(enemie, bullet) {
enemie.remove();
bullet.remove();
score++;
}
function HandlePlayerEnemieCollision(player, enemie) {
enemie.remove();
player.remove();
lives--;
if (lives === 0) {
gameOver = true;
}
createPlayer();
}
/*
function updateEnemie() {
player.setVelocity(7, player.direction);
}
*/
function cheat() {
score = (score + 1000000);
lives = (lives + 1000000);
cheats = 'on';
if (cheats === 'on') {
textSize(50);
fill('yellow');
text('CHEATS ACTIVATED', 400, 300);
}
}
/*
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds) {
break;
}
}
}
*/
function drawGameOverScreen() {
background("black");
textAlign(CENTER);
fill("white");
textSize(40);
text("WELCOME", screenWidth/2, screenHeight/2);
textSize(20);
text("Press SPACE to play!", screenWidth/2, screenHeight/2 + 100);
if (keyWentDown(KEY.SPACE)){
resetGame();
gameOver = false;
}
}
function resetGame(){
score = 0;
lives = 3;
createPlayer();
}
function drawGame() {
background('lightgreen');
drawScoreBoard();
updateplayer();
drawSprites();
shooting();
// updateEnemie();
createEnemie();
}
function draw() {
if (gameOver === true) {
drawGameOverScreen();
} else {
drawGame();
}
}
There is my code, I want to add a time limit for how many seconds it takes until you can shoot again, right now you can just spam and make all of the bullets go in a straight line I need to wait before I let the player shoot again, Thanks! This will help out allot and i neede this in as few minutes as possible.
Use a flag to know when shooting is enabled and disabled. After each shot disable the ability to shoot. Then use a setTimeout to enable the shooting after a certain amount of time.
let shootingEnabled = true;
function tempDisableShooting(duration) {
shootingEnabled = false;
setTimeout(() => {
shootingEnabled = true;
}, duration);
}
function shooting() {
if (shootingEnabled && keyIsDown(KEY.SPACE)) {
if (powerup === 1) {
shoot(3);
} else {
shoot(1);
}
tempDisableShooting(1000); // Disable shooting for 1 second.
}
if (bullet) {
if (bullet.centerX[1] === screenWidth) {
bullets.remove(bullet);
}
}
}
Add property to track the disabled state of the shooting and a constant for the delay time in milliseconds.
let shootDisabled = false;
const shootDelayMS = 300;
Update your shoot function to only shoot if shootDisabled == false, update the shootDisabled to true after each shot, and to triggers a setTimeout which waits shootDelayMS milliseconds before setting shootDisabled to false again.
function shoot(amountofbulletstobeshot) {
if (shootDisabled == false) {
let bulletDirection = [assets.bulletLeft, assets.bulletUp, assets.bulletRight, assets.bulletDown];
let bullet = createSprite(bulletDirection[Math.abs(((Math.round(player.getDirection()/90))))]);
bullets.add(bullet);
bullet.centerX = player.centerX;
bullet.centerY = player.centerY;
bullet.setVelocity(11, player.getDirection());
shootDisabled = true;
setTimeout(() => shootDisabled = false, shootDelayMS );
}
}
one way is the hold the data in two variables: is_shooting, shot_reset.
if(is_shooting){
if(shot_reset>=x){ //x is frame count till able to shoot again)
shot_reset==0;
is_shooting=false;
}else{
shot_reset++
}
}

Won't let me set class name of a Javascript created div

I'm using a function to create a div element on the page. I want to assign a className but I get the error: cannot set property className of undefined.
But I did this in another function and it worked. Why is this one not working?
If I failed to provide the code relevant to the problem I apologize. I'm in a rush and included code that I thought might be relevant in order of relevancy.
** WORKING FUNCTION **
function makeBomb() {
if (player.ready && (player.hasBomb < player.maxBombs)) {
player.score -= 300;
player.hasBomb++;
player.bomb = document.createElement('div');
player.bomb.className = 'bomb'; //DOESN'T THROW ERROR ----
gameArea.appendChild(player.bomb);
player.bomb.x = player.x;
player.bomb.y = player.y;
player.bomb.style.left = player.bomb.x + 'px';
player.bomb.style.top = player.bomb.y + 'px';
player.ready = false;
setTimeout(function () {
player.ready = true;
}, 1000);
}
}
** NOT WORKING FUNCTION **
function makeBullet() {
if (player.enemy.bulletCount < player.enemy.maxBulletCount &&
player.enemy.bulletInterval == true)
player.enemy.bullet = document.createElement('div');
player.enemy.bullet.className = 'bullet'; //THROWS ERROR -----
gameArea.appendChild(player.enemy.bullet);
player.enemy.bullet.x = player.enemy.x;
player.enemy.bullet.y = player.enemy.y;
player.enemy.bullet.style.left = player.enemy.bullet.x +
(player.enemy.offsetWidth / 3) + 'px';
player.enemy.bullet.style.top = player.enemy.bullet.y +
(player.enemy.offsetHeight / 4) + 'px';
player.enemy.bulletCount++;
player.enemy.bulletInterval = false;
setInterval(function(){
player.enemy.bulletInterval = true;
}, 4000);
}
** STARTING CODE THAT MIGHT HAVE CONTEXT IDK**
function start() {
if (player.games === 1) {
gameArea.removeChild(finalScore);
}
gameMessage.style.display = 'none';
score.style.display = "inline-block";
scoreArea.style.display = "inline-block";
text.style.display = "inline-block";
player.inplay = true;
makeEnemy();
player.plane = document.createElement("div");
player.plane.setAttribute("class", "plane");
gameArea.appendChild(player.plane);
player.enemy.x = player.enemy.offsetLeft;
player.enemy.y = player.enemy.offsetTop;
player.x = player.plane.offsetLeft;
player.y = player.plane.offsetTop;
window.requestAnimationFrame(playGame);
}
** OTHER CODE THAT MIGHT HAVE CONTEXT **
function makeEnemy() {
player.enemy = document.createElement('div');
player.enemy.className = 'enemy';
player.enemy.style.left = Math.floor(Math.random() * .
gameArea.offsetWidth - 300) + 100 + 'px';
gameArea.appendChild(player.enemy);
player.enemy.x = player.enemy.offsetLeft;
}
** JUST IN CASE YOU NEED -- idk its hard for me to keep track of everything that might be related to the problem... sorry.. **
title.addEventListener("click", changeColor);
const gameArea = document.querySelector(".gameArea");
const game = document.querySelector(".game");
const scoreArea = document.querySelector(".scoreArea");
const score = document.querySelector(".score");
const text = document.querySelector(".text");
document.addEventListener('keydown', pressOn);
document.addEventListener('keyup', pressOff);
gameMessage.addEventListener('click', start);
let player = {
score: 2000,
speed: 5,
inplay: false,
ready: true,
maxBombs: 4,
hasBomb: 0,
hit: 0,
hitMax: 9,
games: 0,
enemy: {
x: 0
},
getHit: 0,
getHitMax: 20,
swing: false
}
let keys = {
space: false
}
** FULL JS FILE: BE WARNED IM VERY NEW AND THIS IS NOT GOOD CODE **
const title = document.querySelector(".title");
const gameMessage = document.querySelector(".gameMessage");
function changeColor() {
let newArray = ["darksalmon", "lightsalmon", "crimson", "red", "deeppink", "yellowgreen", "ghostwhite"];
let random = Math.floor(Math.random() * Math.floor(newArray.length - 1));
if (title.style.color != newArray[random]) {
title.style.color = newArray[random];
console.log(title.style.color);
} else {
changeColor();
}
}
title.addEventListener("click", changeColor);
const gameArea = document.querySelector(".gameArea");
const game = document.querySelector(".game");
const scoreArea = document.querySelector(".scoreArea");
const score = document.querySelector(".score");
const text = document.querySelector(".text");
document.addEventListener('keydown', pressOn);
document.addEventListener('keyup', pressOff);
gameMessage.addEventListener('click', start);
let player = {
score: 2000,
speed: 5,
inplay: false,
ready: true,
maxBombs: 4,
hasBomb: 0,
hit: 0,
hitMax: 9,
games: 0,
enemy: {
x: 0
},
getHit: 0,
getHitMax: 20,
swing: false
}
let keys = {
space: false
}
function start() {
if (player.games === 1) {
gameArea.removeChild(finalScore);
}
gameMessage.style.display = 'none';
score.style.display = "inline-block";
scoreArea.style.display = "inline-block";
text.style.display = "inline-block";
player.inplay = true;
makeEnemy();
player.plane = document.createElement("div");
player.plane.setAttribute("class", "plane");
gameArea.appendChild(player.plane);
player.enemy.x = player.enemy.offsetLeft;
player.enemy.y = player.enemy.offsetTop;
player.x = player.plane.offsetLeft;
player.y = player.plane.offsetTop;
window.requestAnimationFrame(playGame);
}
function playGame() {
if (player.inplay) {
moveBomb();
if(player.x < (gameArea.offsetWidth / 2)) {
console.log('WORKED');
makeBullet();
}
if (player.swing){
player.plane.style.backgroundImage ='url(guts1.png)';
player.swing = false;
//player.plane.style.width = 210 + 'px';
}
if (keys['x'] && player.enemy && isCollide(player.plane, player.enemy)) {
removeEnemy();
}
if (player.enemy) {
if (isCollide(player.plane, player.enemy)) {
player.getHit++;
if (player.getHit > player.getHitMax){
endGame();
}
} else {
player.getHit = 0;
}
if (player.x > player.enemy.x) {
player.enemy.x += 1;
}
if (player.x < player.enemy.x) {
player.enemy.x -= 1;
}
player.enemy.style.left = player.enemy.x + 'px';
}
if (player.hasBomb >= player.maxBombs && player.bomb.y > gameArea.offsetHeight - 20) {
endGame();
}
if (keys.space) {
makeBomb()
}
if (keys.ArrowUp && player.y > 0) {
player.y -= (player.speed + (player.speed * .5));
}
if (keys.ArrowDown && player.y < (gameArea.offsetHeight - player.plane.offsetHeight - 30)) {
player.y += (player.speed + (player.speed * .5));
}
if (keys.ArrowLeft && player.x > 0) {
player.x -= (player.speed + (player.speed * .5));
}
if (keys.ArrowRight && player.x < (gameArea.offsetWidth)) {
player.x += (player.speed - (player.speed * .5));
}
if (player.x == (gameArea.offsetWidth)) {
player.x = 0;
player.score -= 100;
if (!player.enemy) {
makeEnemy();
}
}
player.score -= .4;
if (player.score < 0) {
player.score = 0;
}
player.x += (player.speed * .5);
score.innerHTML = Math.floor(player.score) + ' Bombs left: ' + (player.maxBombs - player.hasBomb);
player.plane.style.left = player.x + 'px';
player.plane.style.top = player.y + 'px';
window.requestAnimationFrame(playGame);
}
}
function pressOn(e) {
e.preventDefault();
let tempKey = (e.key == " ") ? "space" : e.key;
keys[tempKey] = true;
if (keys['x'] && player.swing == false){
playerPlane = player.plane;
player.plane.style.backgroundImage ='url(guts2.png)';
setTimeout(function () {
player.swing = true;
}, 300);
//player.plane.style.width = 400 + 'px';
}
console.log(tempKey)
console.log(keys);
}
function pressOff(e) {
e.preventDefault();
let tempKey = (e.key== " ") ? "space" : e.key;
console.log(tempKey);
// if (keys['x'] && player.swing){
// playerPlane = player.plane;
// player.plane.style.backgroundImage ='url(guts1.png)';
// player.swing = false;
// //player.plane.style.width = 210 + 'px';
//
// }
if (keys['space'] || keys['x']) {
keys['space'] = 0;
keys['x'] = 0;
}
keys[tempKey] = false;
console.log(keys);
}
function moveBomb() {
let bombs = document.querySelectorAll('.bomb');
bombs.forEach(function (item) {
item.y += 10;
item.style.top = item.y + 'px';
if (item.y > gameArea.offsetHeight) {
item.parentNode.removeChild(item);
player.bomb = null;
}
if (player.enemy && player.bomb) {
if (isCollide(item, player.enemy)) {
player.hit++;
}
}
if (player.hit > player.hitMax) {
item.parentNode.removeChild(item);
player.bomb = null;
player.score += 2000;
player.hit = 0;
player.hasBomb -= 2
gameArea.removeChild(player.enemy);
player.enemy = null;
}
})
}
function makeEnemy() {
player.enemy = document.createElement('div');
player.enemy.className = 'enemy';
player.enemy.style.left = Math.floor(Math.random() * gameArea.offsetWidth - 300) + 100 + 'px';
gameArea.appendChild(player.enemy);
player.enemy.x = player.enemy.offsetLeft;
}
//function getLocationX(a){
// let aRect = a.getBoundingClientRect();
// let aX = aRect.x;
// return aX;
// //w console.log(aX);
//}
//
//function getLocationY(a){
// let aRect = a.getBoundingClientRect();
// let aY = aRect.y;
// return aY;
// // console.log(aY);
//}
function isCollide(a, b) {
let aRect = a.getBoundingClientRect();
let bRect = b.getBoundingClientRect();
return !(
(aRect.bottom < bRect.top) ||
(aRect.top > bRect.bottom) ||
(aRect.right < bRect.left) ||
(aRect.left > bRect.right)
)
}
function makeBomb() {
if (player.ready && (player.hasBomb < player.maxBombs)) {
player.score -= 300;
player.hasBomb++;
player.bomb = document.createElement('div');
player.bomb.className = 'bomb';
gameArea.appendChild(player.bomb);
player.bomb.x = player.x;
player.bomb.y = player.y;
player.bomb.style.left = player.bomb.x + 'px';
player.bomb.style.top = player.bomb.y + 'px';
player.ready = false;
setTimeout(function () {
player.ready = true;
}, 1000);
}
}
function makeBullet() {
if (player.enemy.bulletCount < player.enemy.maxBulletCount && player.enemy.bulletInterval == true)
player.enemy.bullet = document.createElement('div');
player.enemy.bullet.className = 'bullet';
gameArea.appendChild(player.enemy.bullet);
player.enemy.bullet.x = player.enemy.x;
player.enemy.bullet.y = player.enemy.y;
player.enemy.bullet.style.left = player.enemy.bullet.x + (player.enemy.offsetWidth / 3) + 'px';
player.enemy.bullet.style.top = player.enemy.bullet.y + (player.enemy.offsetHeight / 4) + 'px';
player.enemy.bulletCount++;
player.enemy.bulletInterval = false;
setInterval(function(){
player.enemy.bulletInterval = true;
}, 4000);
}
function endGame() {
if (player.enemy) {
gameArea.removeChild(player.enemy);
}
gameArea.removeChild(player.plane);
if (player.bomb){
gameArea.removeChild(player.bomb);
player.bomb = null;
}
score.style.display = 'none';
scoreArea.style.display = 'none';
text.style.display = 'none';
gameMessage.style.display = 'inline-block';
player.inplay = false;
player.hasBomb = 0;
finalScore = document.createElement('div');
finalScore.classList.add('finalScore');
finalScore.innerHTML = 'YOU SCORED: ' + Math.floor(player.score);
gameArea.appendChild(finalScore);
player.games = 1;
player.getHit = 0;
}
function removeEnemy() {
gameArea.removeChild(player.enemy);
player.enemy = null;
player.score += 2000;
}
function makeBullet() {
if (player.enemy.bulletCount < player.enemy.maxBulletCount &&
player.enemy.bulletInterval == true)
youre missing curly braces at the end of the if statement and i think its interpretting the next line as a part single line if statement
change to
function makeBullet() {
if (player.enemy.bulletCount < player.enemy.maxBulletCount &&
player.enemy.bulletInterval == true) {
...
...
...
}
}

Vanilla Javascript animate margin-left of section

I'm having an issue getting my slider to work. It's a simple system of clicking buttons to get to and from sections but I'm having issues getting it to work.
I have made a codepen here: https://codepen.io/ItsBrianAgar/pen/JrbZEz
This is the js I have so far.
It needs to be Vanilla Js
var nextSection = function() {
var username = document.querySelector("input[name=\"username\"]").value;
var password = document.querySelector("input[name=\"password\"]").value;
if (username.length && password.length > 4) {
return window.location = "appSection.html";
} else {
alert("username and password must be longer than 4 characters");
}
}
var nextPage = function() {
var elem = document.getElementsByClassName("app");
var pos = 0;
var posDiff = 0;
var currentPos = elem[1].style.marginLeft;
var id = setInterval(frame, 5);
function frame() {
if (posDiff == -320) {
clearInterval(id);
posDiff = 0;
} else {
pos--;
for (var i = 0; i < elem.length; i++) {
elem[i].style.marginLeft = pos + 'px';
}
posDiff = currentPos + pos;
}
}
}
document.getElementById("cancel").onclick = previousPage = function() {
var elem = document.getElementsByClassName("app");
var pos = 0;
var id = setInterval(frame, 5);
function frame() {
for (var i = 0; i < elem.length; i++) {
if (pos == 640) {
clearInterval(id);
} else {
elem[i].style.marginLeft = pos + 'px';
pos += 320;
}
}
}
}
You can use Element.animate() to animate a DOM element
const [div, animationState, props] = [
document.querySelector("div")
, ["click to animate", "click to reverse animation"]
, ["0px", "320px"] // from, to
];
div.textContent = animationState[0];
div.onclick = () => {
div.animate({
marginLeft: props
}, {
duration: 1000,
easing: "linear",
iterations: 1,
fill: "both"
})
.onfinish = function() {
props.reverse();
div.textContent = animationState.reverse()[0];
}
}
<div></div>

JS Thumb scroller

I have a thumb scroller on my site and the problem is, when thumbs reach end scroller leaves blank spaces before it goes back to beginning... Can anyone help how to achive this... Thank you in advance!
This is the url: http://marinmartinovic.com/MK_test/
It could take a little bit to load. Still need to optimize images...
This is js:
$(document).ready(function(event) {
/*
*
* SORTING INDEX NUMBERS
*
*/
function sortIndexNumbers(){
loadPhotoIndex = 0;
indexNumbers = [];
for(var i = 0; i<photosLength;i++){
indexNumbers.push(i);
}
if(photoIndex === 0){
indexNumbersToAdd = indexNumbers.splice(photosLength-1, 1);
indexNumbers = indexNumbersToAdd.concat(indexNumbers);
}
if(photoIndex > 1){
indexNumbersToAdd = indexNumbers.splice(0, photoIndex -1);
indexNumbers = indexNumbers.concat(indexNumbersToAdd);
}
loadPhoto();
}
/*
*
* LOAD THUMBS
*
*/
var aThumbsWidth = [];
var speedThumb = 750;
var thumbIndex = 0;
var thumbSwiped = 0;
var thumbsWidth = 0;
function loadThumb(){
$('<img src="'+ aThumbs[thumbIndex] +'">').one('load', function() {
$(".thumb-content ul").append('<li><div class="thumb" id="thumb" data-index=' + thumbIndex + '><img src="'+ aThumbs[thumbIndex] +'"></div></li>');
//setTimeout(function() {
aThumbsWidth.push($('.thumb-content .thumb img').get(thumbIndex).width);
thumbsWidth+= $('.thumb-content .thumb img').get(thumbIndex).width + thumbSpacing;
thumbIndex++;
if(thumbIndex < aThumbs.length){
loadThumb();
}
// all 3 loaded
if(thumbIndex === aThumbs.length){
highlightThumb();
// find thumb and get its position
console.log(photoIndex);
var thumbPosition = $('.thumb-content').find("[data-index='" + photoIndex + "']").position().left;
selectThumb(thumbPosition);
}
//}, 50);
}).each(function() {
//if(this.complete) $(this).load();
});
}
/*
*
* SWIPE THUMB SLIDER
*
*/
var currentThumb = 0;
var currentThumbShift = 0;
$(".thumb-content").swipe( {
tap:function(event, target) {
if(!loadingInProgress){
photoIndex = parseFloat(target.getAttribute('data-index'));
selectPhoto();
highlightThumb();
}
},
triggerOnTouchEnd: false,
swipeStatus: swipeThumbStatus,
allowPageScroll: "vertical",
threshold: 200
});
function swipeThumbStatus(event, phase, direction, distance, fingers)
{
thumbSwiped = distance;
/*if( phase === "move" && (direction === "left" || direction === "right") )
{
var duration = 0;
if (direction === "left"){
scrollThumbs(currentThumbShift + distance, duration);
}
else if (direction === "right"){
scrollThumbs(currentThumbShift - distance, duration);
}
}
else if ( phase === "cancel")
{
scrollThumbs(currentThumbShift, duration);
}*/
if ( phase === "end" ){
if (direction === "right"){
if(!loadingInProgress){
prevPhoto();
setThreePhotos(prevPhoto, 1500, 1);
}
}
else if (direction === "left"){
if(!loadingInProgress){
nextPhoto();
setThreePhotos(nextPhoto, 1500, 1);
}
}
}
}
function selectThumb(distance){
currentThumb = currentThumb + photoIndex;
TweenLite.to($(".thumb-content"), 0.75, {left: -distance, ease:Power4.easeOut, force3D:true});
}
$('body').on('click', '.thumb', function(e) {
if(!loadingInProgress){
photoIndex = parseFloat($(this).attr('data-index'));
selectPhoto();
highlightThumb();
selectThumb($(this).position().left);
}
});
function highlightThumb(){
$('.thumb').css('opacity', '1');
$('.thumb-content').find("[data-index='" + photoIndex + "']").css('opacity', '0.5');
}
/*
*
* NEXT PREVIOUS THUMB
*
*/
var arrow = false;
var nextThree ;
var intervalBuffer;
$('#next-thumb').click(function(event) {
if(!loadingInProgress){
photoIndex += 2;
if((photoIndex+1) >= aPhotos.length){
photoIndex = 0;
}
selectPhoto();
highlightThumb();
// find thumb and get its position
var thumbPosition = $('.thumb-content').find("[data-index='" + photoIndex + "']").position().left;
selectThumb(thumbPosition);
}
});
$('#prev-thumb').click(function(event) {
if(!loadingInProgress){
photoIndex -= 2;
if((photoIndex+1) < 0){
photoIndex = aPhotos.length-1;
}
selectPhoto();
highlightThumb();
// find thumb and get its position
var thumbPosition = $('.thumb-content').find("[data-index='" + photoIndex + "']").position().left;
selectThumb(thumbPosition);
}
});
function setThreePhotos(callback, delay, repetitions) {
clearInterval(threePhotos);
var x = 0;
var threePhotos = setInterval(function () {
callback();
if (++x === repetitions) {
clearInterval(threePhotos);
}
}, delay);
}

js only execute at a certain time?

i write this code to make a basic game. The full html is:
<!DOCTYPE>
<html>
<head>
<title>The dodge game</title>
<link rel="stylesheet" type="text/css" href="normalize.css">
<link rel="stylesheet" type="text/css" href="index.css">
<script src="jquery.js"></script>
<script src="script.js"></script>
</head>
<body>
<div id="play-ground">
<div id="character"></div>
<div id="chaser"></div>
</div>
<button id="control-up" class="button">UP</button>
<button id="control-down" class="button">DOWN</button>
<button id="control-right" class="button">RIGHT</button>
<button id="control-left" class="button">LEFT</button>
</body>
</html>
the script :
$(document).ready (
function() {
var characterPositionLeft = 0;
var characterPositionTop = 0;
var chaserPositionLeft = 810;
var chaserPositionTop = 630;
var speed = 30;
var dspeed = 60;
var apoint = 5;
var testPositionLeft = function() {
if (chaserPositionLeft > characterPositionLeft) {
chaserPositionLeft -= 30;
var caLeft = chaserPositionLeft + 'px';
$('#chaser').css('margin-left', caLeft);
leftRight();
topBottom();
testEndGame();
console.log(chaserPositionLeft);
} else if (chaserPositionLeft < characterPositionLeft) {
chaserPositionLeft += 30;
var caLeft = chaserPositionLeft + 'px';
$('#chaser').css('margin-left', caLeft);
leftRight();
topBottom();
testEndGame();
console.log(characterPositionLeft);
}
}
var testPositionTop = function() {
if (chaserPositionTop > characterPositionTop) {
chaserPositionTop -= 30;
var caTop = chaserPositionTop + 'px';
$('#chaser').css('margin-top', caTop);
leftRight();
topBottom();
testEndGame();
console.log(chaserPositionTop);
} else if (chaserPositionTop < characterPositionTop) {
chaserPositionTop += 30;
var caTop = chaserPositionTop + 'px';
$('#chaser').css('margin-top', caTop);
leftRight();
topBottom();
testEndGame();
console.log(chaserPositionTop);
}
}
// left and right
var CacLeftPlus = chaserPositionLeft + 30;
var CacLeftMinus = chaserPositionLeft - 30;
var LeftCaught = false;
// top and bottom
var CacTopPlus = chaserPositionTop + 30;
var CacTopMinus = chaserPositionTop - 30;
var TopCaught = false;
// up
$('#control-up').click (
function() {
testPositionTop();
if(characterPositionTop > 0) {
characterPositionTop -= speed;
var cTop = characterPositionTop + 'px';
console.log(characterPositionTop);
$('#character').css('margin-top', cTop);
leftRight();
topBottom();
testEndGame();
} else {
console.log('warning: [reached sky limit]');
}
}
)
// down
$('#control-down').click (
function() {
testPositionTop();
if(characterPositionTop < 630) {
characterPositionTop += speed;
var cTop = characterPositionTop + 'px';
console.log(characterPositionTop);
$('#character').css('margin-top', cTop);
leftRight();
topBottom();
testEndGame();
} else {
console.log('warning: [reached earth limit]');
}
}
)
// right
$('#control-right').click (
function() {
testPositionLeft();
if(characterPositionLeft < 810) {
characterPositionLeft += speed;
var cTop = characterPositionLeft + 'px';
console.log(characterPositionLeft);
$('#character').css('margin-left', cTop);
leftRight();
topBottom();
testEndGame();
} else {
console.log('warning: [reached right limit]');
}
}
)
// left
$('#control-left').click (
function() {
testPositionLeft();
if(characterPositionLeft > 0) {
characterPositionLeft -= speed;
var cTop = characterPositionLeft + 'px';
console.log(characterPositionLeft);
$('#character').css('margin-left', cTop);
leftRight();
topBottom();
testEndGame();
} else {
console.log('warning: [reached left limit]');
}
}
)
var leftRight = function() {
if(characterPositionLeft == CacLeftPlus || characterPositionLeft == CacLeftMinus) {
LeftCaught = true;
console.log('worked?');
} else {
}
}
var topBottom = function() {
if(characterPositionTop == CacTopPlus || characterPositionLeft == CacTopMinus) {
TopCaught = true;
console.log('worked?');
} else {
}
}
var testEndGame = function () {
if (LeftCaught == true && TopCaught == true) {
console.log('game over');
alert('game over');
} else {
}
}
}
)
Everything works fine until the functions leftRight, upBottom and testEndGame. They only console worked when the console is logged 600 and 630. Can anyone please tell me the flaw in this code and a way to fix this? Here is the full code: http://jsfiddle.net/StK7r/1/
I believe you want
if(characterPositionTop == CacTopPlus || characterPositionLeft == CacTopMinus) {
to instead test
if(characterPositionTop <= CacTopPlus && characterPositionTop >= CacTopMinus) {
because you intend your character to be caught inside a box. Same for left. Also, you were testing your 'top' position against your 'left'.
EDIT later:
I've updated the fiddle a bit. I noticed this also:
// left and right
var CacLeftPlus = chaserPositionLeft + 30;
var CacLeftMinus = chaserPositionLeft - 30;
var LeftCaught = false;
// top and bottom
var CacTopPlus = chaserPositionTop + 30;
var CacTopMinus = chaserPositionTop - 30;
You are not updating these variables when chaserPositionTop/Left changes. They are being bound by value here, so obviously they remained forever at the value you are giving them in the initializer.

Categories