I want to get a div ball to move left using javascript and
document.getElementById("ball").style.left = i + "px";
This is the code that i'm using (below). I was thinking to use the while(true) {} loop, but it just crashed on me...
Does anyone know how to do/fix this??
JSFiddle
<script>
//while(true) {
var ballLeft = 250;
document.getElementById("ball").style.left = ballLeft;
ballLeft =-2;
// }
</script>
EDIT
The <script> tag is placed inside the <body>
EDIT 2
My issue is that the ball is not moving.
JavaScript is single-threaded (with some very specific exceptions that do not apply here). That single thread executes tasks one at a time, exclusively. Executing a script is one task. Repainting the browser is another; answering a click is yet another. If you run an infinite task (like a while (true) { ... }), the browser will never again have time to interact with you.
Make sure any infinite loop is broken up by frequent timeouts, or - even better, for an animation job - use window.requestAnimationFrame().
const ball = document.getElementById('ball');
let position = 250;
function tick(ts) {
ball.style.left = `${position}px`;
position -= 2;
if (position > 0) window.requestAnimationFrame(tick);
}
window.requestAnimationFrame(tick);
#ball {
position: absolute;
left: 250px;
top: 0;
}
<div id="ball">
🏀
</div>
Related
I'm trying to create a border that slowly wraps around the screen. As part of this process, I'm playing around with only increasing the height of the border right now by using the setInterval method. However, I can't get the border height to increase slowly. Below is what I'm doing:
var i = 1;
setBorder = setInterval(borderAnimation(), 200);
function borderAnimation() {
var border = document.getElementById("border-animation");
border.style.height = i + "vh";
i = i + 1;
document.write(i);
if(i = 100){
clearInterval(setBorder);
}
}
document.write(2);
If I change the variable i inside the function to say 5, then the height changes to that number so I know the function is being called at least once.
Similarly, document.write(i) prints only once. So if i is 1, then in the screen I see only 1; it also does not print 2 at any time even though I have document.write(2). Why is this?
After this, I intend to make it so that another div is called that goes around the top (this one is left), then another on the right then another around bottom, thus completing a border that goes around the screen. If someone has a better idea or way of achieving this, please let me know as well.
There are a couple mistakes:
1: pass the function reference (don't call the function) to setInterval
2: if(i = 100) should be if(i == 100)
var i = 1;
setBorder = setInterval(borderAnimation, 200);
function borderAnimation() {
var border = document.getElementById("border-animation");
border.style.height = i + "vh";
i = i + 1;
console.log(i);
if(i == 20){
clearInterval(setBorder);
}
}
#border-animation{
position: absolute;
width: 200px;
border: 1px solid #333;
}
<div id="border-animation"><div>
Here I have an odd problem. I'm building a simple helicopter game (the old type - click to go up, avoid obstacles). My problem is that the obstacles generate, but don't position correctly, and then they won't move. I'm trying to move them with jQuery's css() - the css method works fine on anything else but when used with top and left doesn't.
The problem functions (generate and move obstacles):
game.background.generateObs = function() {
var top = Math.floor(Math.random()*game.canvas.height);
var left = game.canvas.width-10;
var $obs = $("<div></div>")
$obs.addClass("obs").appendTo("#canvas");
$obs.css({
background: "black",
position: "absolute",
height: game.obstacle.height,
width: game.obstacle.width,
});
$obs.css("top", $("#canvas").offset().top + top )
.css("left",$("#canvas").offset().left + left);
game.obstacle.width = Math.floor(Math.random()*200);
if(game.gameState=="running") {
setTimeout("game.background.generateObs()",obsInterval);
}
else {
return;
}
}
game.background.moveObs = function() {
var currentPos = $("#canvas div.obs").css("left");
var newPos = currentPos - game.obstacle.frameWidth;
$("#canvas div.obs").css("left",newPos);
if(game.gameState=="running") {
setTimeout("game.background.moveObs()",interval);
}
else {
return;
}
}
The other thing is that jsFiddle is now telling me that game is undefined, when I have defined it right at the start.
Can anyone tell me what I'm doing wrong? Here's the fiddle.
$("#canvas div.obs").css("left") is returning auto in your fiddle, not a number.
Try using .offset().left instead.
Additionally, you should change your setTimeout calls like this:
setTimeout(game.background.moveObs,interval);
I'm developing a Fez-based HTML5 Canvas game using EaselJS and I've found a problem, that I can't solve myself, while trying to implement SpriteSheets to the hero.
The problem is that I've defined three animations to my hero ("stand", "jump" and "run") and when I try to change from one animation to another using hero.gotoAndPlay("run") or hero.gotoAndStop("stand") the animations don't change, change but show the first frame only or change to the wrong animation.
Can someone help me? What I'm doing wrong and how can I fix it? Thanks.
Here's the relevant JavaScript code I'm using to create the hero Sprite:
var data = {
images: ["http://i.imgur.com/M0GmFnz.png"],
frames: {width:34, height:46},
animations: {
stand:0,
run:[0,12,true,0.25],
jump:13
}
};
var spriteSheet = new createjs.SpriteSheet(data);
var hero = new createjs.Sprite(spriteSheet, "stand");
hero.offset = 4 + 1; // "+1" is important, change the first number only.
hero.regX = hero.offset + 2;
hero.regY = hero.offset;
hero.width = 34 - (hero.offset*2) - 12;
hero.height = 46 - (hero.offset*2);
hero.x = 0;
hero.y = 0;
hero.jumping = true;
stage.addChild(hero);
And the code I'm using to change the animation:
if(!left && !right){ // User isn't pressing left arrow or right arrow
hero.gotoAndStop("stand");
}else{
hero.gotoAndPlay("run");
}
JSFiddle
Official Site
If you are calling gotoAndStop or gotoAndPlay in a tick (or similar) then it will constantly reset to the first frame. You have to ensure you only call these functions one time when the animation changes.
A good way to set this up is to store the current animation, store it, and only change it up if the animation changes. Something like:
var animation;
if(!left && !right){ // User isn't pressing left arrow or right arrow
animation = "stand";
}else{
animation = "run";
}
if (currentAnimation != animation) {
hero.gotoAndStop(animation);
}
This is just an example, but should give you an idea. You should only call these methods one time to kick off an animation.
I had an idea for like a bus window as a fixed frame, about 800px wide, with a parallax city with the content on billboards spaced out so when you scroll between them it allows the parallax to look like bus is moving. The content will be much bigger than the window like a sprite and I'll put forward and back buttons that will scrollBy (x amount, 0). I have a working parallax script and a rough cityscape of 3 layers that all work fine.
I have hit a wall. I am trying to clear a scrollBy animation after it scrolls 1000px. Then you click it again and it goes another 1000px. This is my function.
function scrollForward() {
window.scrollBy(5,0);
scrollLoop = setInterval('scrollForward()',10);
}
So far I can only clear it when it gets to 1000. I tried doing 1000 || 2000 ect but after the first one it goes really fast and won't clear.
Excelsior https://stackoverflow.com/users/66580/majid-fouladpour wrote a great piece of code for someone else with a different question. It wasn't quite right for what the other guy wanted but it is perfect for me.
function scrollForward() {
var scrolledSoFar = 0;
var scrollStep = 75;
var scrollEnd = 1000;
var timerID = setInterval(function() {
window.scrollBy(scrollStep, 0);
scrolledSoFar += scrollStep;
if( scrolledSoFar >= scrollEnd ) clearInterval(timerID);
}, 10);
}
function scrollBack() {
var scrolledSoFar = 0;
var scrollStep = -75;
var scrollEnd = -1000;
var timerID = setInterval(function() {
window.scrollBy(scrollStep, 0);
scrolledSoFar += scrollStep;
if( scrolledSoFar <= scrollEnd ) clearInterval(timerID);
}, 10);
}
Now for step two figuring out how to put this content animation behind a frame.
Not quite sure what your asking here. Perhaps you could provide more relevant code?
I do see a potential issue with your code. You call setInterval('scrollForward()', 10) which will cause scrollForward to be called every 10ms. However, each of those calls to scrollForward will create more intervals to scrollForward creating a sort of explosion of recursion. You probably want to use setTimeout or create your interval outside of this function.
Also, as an aside you can change your code to simply: setInterval(scrollForward, 10). Removing the quotes and the parens makes it a littler easier to read and manager. You can even put complex, lambda functions like:
setInterval(function() {
scrollForward();
// do something else
}, 10);
edit:
So if you know that scrollForward moves the item 10px, and you want it to stop after it moves the item 1000px, then you simply need to stop it has moved that much. I still don't know how your code is actually structured, but it might look something like the following:
(function() {
var moved_by = 0;
var interval = null;
var scrollForward = function() {
// move by 10px
moved_by += 10;
if (moved_by === 1000 && interval !== null) {
clearInterval(interval);
}
};
var interval = setInterval(scrollForward, 10);
})();
If you want to clear it after 1000 or 2000, you simply adjust the if statement accordingly. I hope that helps.
I am trying to create a sort of slideshow animation. I have the codes here: jsFiddle.
These tablets would rotate around.
The problem is that, at random times, the animation will move out of line. The wrong tablets undergo wrong animations. Here are the screenshots:
And this is how it looks like when the animations goes wrong
The main problem is I don't understand why the animation would go wrong random times. In my computer it will run properly for hours, but in other cases (especially on Safari).
You could store the expected final css values for each animated el and then in the animate callback set these values, so for each animated el something like
var el = $(selector);
el.data("finalCSS", { your expected final CSS values })
$("selector").animate({animation properties}, function() {
el.css(el.data("finalCSS")).data("finalCSS", undefined);
})
This doesn't help with figuring out why it's happening (but I can't recreate the issue myself), but provides a failsafe to make sure the layout doesn't break;
I believe this happens when you try to animate before the previous animation has ended. Use jQuery stop() just before you animate. For example:
$('#animatingDiv').stop(false, true).animate({height:300}, 200, callback);
The first param(false) will empty the animation queue on that element and the second param(true) will jumps to the end of current animation before starting a new animation.
You can do this with far less code and far fewer headaches.
1. Store your tablet position attributes in classes
.tablet1{
height:100px;
width:140px;
margin-left:-540px;
top: 200px;
z-index:10;
}
2. Use a general function to handle all your transitions.
JQuery UI will do all the work for you if you use switchClass
switchTabletsRight = function(){
var i, next, max = 5;
for(i = 1; i <= max; i++){
next = (i < max)? i + 1 : 1;
$(".tablet" + i).switchClass("tablet" + i, "tablet" + next);
}
};
Here's the JSfiddle proof of concept: http://jsfiddle.net/nRHag/4/
You are setting CSS positions to decimal values.
img_w = $("#tablet"+num+" img").width();
img_w = img_w *140 / 600;
img_h = $("#tablet"+num+" img").height();
img_h = img_h *140 /600;
...
var new_width = $(this).width() * 140 / 600;
$(this).css('width', new_width);
var new_height = $(this).height() * 140 / 600;
$(this).css('height', new_height);
Your division could be cause decimal results which have different effects in different browsers. Sub pixel CSS positioning may be creating your unintended errors.