Javascript loop - hide animated div - javascript

I'm going to try to make this as descriptive as possible, my apologies in advance if I have difficulties explaining what it is exactly that I am trying to do.
Written Description:
So I am creating a web based game in javascript. This game is a 2 player shooter game. So far, when a player 'shoots' another player, it spawns an animated div which goes from its start (at the gun of player1) to the end of the screen where it then gets removed (using removeChild from the div it was spawned in.)
The problem is that when the bullet 'hits' the player, it jsut keeps on going until the end of the screen. My code does register whether or not the bullet hits the player, but when it does hit the player, I would like it to dissappear either on the player or right after it passes the player, so that it has the effect that it penetrates the player instead of just passing over the player.
Now let me be more specific.
$("#bullet").animate({
marginLeft: '100%'
}, 1000, function(){
document.getElementById("thegame").removeChild("#bullet");
});
basically this is the code that spawns the 'bullet'
now lets say that I wanted to get the bullet to disappear after it's margin passed 70% by doing some sort of loop that checks its position as the animated div is traveling..
how would I do this? (the bullet is #bullet)
I tried doing a loop for this but i must have failed because it didn't work.

Use step option of .animate() , .stop()
var money = $("#thegame span")[0];
$("#bullet").animate({
marginLeft: '100%'
}, {
duration: 1000,
step: function(now, fx) {
// calling `.stop()` triggers `.fail` callback
if (now > 70) $(fx.elem).stop()
},
done: function() {
document.getElementById("thegame").removeChild(money);
},
fail: function() {
document.getElementById("thegame").removeChild(money);
console.log(this, this.style.marginLeft)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="bullet">abc</div>
<div id="thegame"><span>thegame</span></div>

Use setTimeout()for this purpose,
function myfun(){
setTimeout(function(){$("#welcome").show(100)}, 2000);
setTimeout(function(){$("#welcome").hide(500)}, 7000);
}
setInterval()would invoke the supplied code for every time interval that you gave

Related

Animation not being made jquery (backgroundColor)

I'm having a problem where I'm making a function in JavaScript (JQuery):
$('.login').click( function() {
$('#login-container').animate({
left: 0
}, 300, "swing", function(){
$('#login-container').animate({
backgroundColor: 'rgba(0,0,0,0.4)'
}, 2000, "swing");
});
});
Whereas "login" is a button and login-container is a big div which contains a form which people can use to login.
I'm trying to make the giant container that slides over the page only turn its background color to lower the website's exposure but it's working and as far as I know, the code is correct.
The first animation happens but the second one (referring to the backgroundColor) doesn't even start at all.
Thanks in advance
EDIT:
I've simplified my code to see if it was a problem of my syntax or JS simply not applying this animation:
$('.login').click( function() {
$('#login-container').animate({
backgroundColor: 'rgba(0,0,0,0.4)'
}, 2000, "swing");
});
And the element does not have its background-color applied, for some reason.
I don't actually get what you're trying to say here, but if you want to toggle that animation you can use $.toggle() of jquery after the user clicks.
If you want to animate this stuff, look at this documentation provided by jQuery
jQuery Animation

Interval doesn't clear immediately after repeating for a while

I have a bouncing arrow on my website that I created with Jquery and setInterval, like this:
bouncing = setInterval(function() {
$("div").animate({
top:"30px"
},100,"easeInCubic",function() {
$("div").animate({
top:"0px"
},100,"easeOutCubic");
});
console.log("bounced");
},200);
You can see this in place in a codepen here: http://codepen.io/mcheah/pen/wMmowr
I made it run faster than i needed because its easier to see the issues quicker. My issue is that after leaving the interval running for a few seconds, you'll notice that instead of bouncing back up or down immediately, the bouncing element will stop for half a second and then just hang there, before beginning again. If you leave it running even longer (20 seconds) and then clear the interval, you'll notice that it takes a few seconds to stop bouncing.
My questions are these:
Why does the bouncing go out of sync occasionally?
Why does the clear interval take a while to clear if it's been repeating for a while?
Is there a better way to have a bouncing arrow? Are CSS transitions more reliable?
Thanks for your help!
Your are trying to perfectly coordinate a setInterval() timer and two jQuery animations such that the two come out perfectly coordinated. This is asking for trouble and the two may drift apart over time so it is considered a poor design pattern.
If, instead, you just use the completion of the second animation to restart the first and make your repeat like that, then you have perfect coordination every time.
You can see that here in another version of your codepen: http://codepen.io/anon/pen/NxYeyd
function run() {
var self = $("div");
if (self.data("stop")) return;
self.animate({top:"30px"},100, "easeInCubic")
.animate({top:"0px"}, 100, "easeOutCubic", run);
}
run();
$("div").click(function() {
// toggle animation
var self = $(this);
// invert setting to start/stop
self.data("stop", !self.data("stop"));
run();
console.log("toggled bouncing");
});
It's not a good idea to mix animate() with timers this way. There's NO chance you can synchronize something like this. And there's no need to. You can simply append a function into the animation queue, look here: https://stackoverflow.com/a/11764283/3227403
What animate() does is put an animation request into a job queue which will be processed later, when the right time comes. When you break the interval the stuff that accumulated in the queue will still be processed. There's a method to clear the queue and stop all animation immediately.
The JQuery animation functions actually manipulate CSS, and there is nothing beyond it in HTML. Another option would be using a canvas, but it is a completely different approach and I wouldn't recommend it. With JQuery's animation your already at the best choice.
This is a simple solution to your problem:
function bounce()
{
$("div")
.animate({
top: "30px"
}, 100, "easeInCubic")
.animate({
top: "0px"
}, 100, "easeOutCubic", bounce); // this loops the animation
}
Start bouncing on page load with:
$(bounce);
Stop bouncing on click with:
$("div").click(function() {
$("div").stop().clearQueue().css({ top: "0px" });
// you want to reset the style because it can stop midway
});
EDIT: there were some inaccuracies I corrected now. The running example is on codepen now.
If you want to use javascript for animation you can use something better like the greensock tween library
http://greensock.com/docs/#/HTML5/GSAP/TweenMax/to/
something like this:
var tween = TweenMax.to($("div"), 100, {y: "100px", yoyo: true, repeat: -1});
You could wrap your interval code with:
if(!$("div").is(":animated"))
This will initiate your animation only if your previous one is finished.
The reason why it was bouncing weird is that your animations are queued.
You can check how it works now:
http://codepen.io/luminaxster/pen/XKzLBg
I would recommend using the complete callback when the second animation ends instead and have variable to control a bounce recursive call in this version:
http://codepen.io/luminaxster/pen/qNVzLY

There is a javascript delay when hovering over images

I have four images on a page and when I hover over the image, I want a horizontal div to move up on the bar, and when the mouse pointer moves off of the image, I want it to slide back down. Now when I do this is works fine, however there seems to be a delay. Also, if I move back and forth repeatedly, the delay is more and the slider ends up going up and down on its own for a few seconds. Here is the code, please help!
$('.indexgall').on('mouseenter',function()
{
$(this).addClass('hoverimg');
$(this).children().animate(
{
top: 150
}, 600, function()
{
});
});
$('li').on('mouseleave',function()
{
$(this).removeClass('hoverimg');
$(this).children().animate(
{
top:250,
}, 600, function()
{
});
});
From your code, it doesn't look there should be a delay. Can you post a JSFiddle to show this problem in action?
To address the latter concern, you want to be using the JQuery stop() method to stop the animation by cleaning the animation queue.
This can be done, like so:
$(this).stop().animate({
width: 240
}, 500);
Check out this JSFiddle.

jquery animate callback not executing until final loop

I made a small test code using the jquery transit plugin for animations.
The purpose of the script is to have a photo of a tower make a flip 90 degrees toward the user, switch to another tower image, and flip another 90 degrees to lay flat on the screen. The issue is that after the first 90 degree flip, the image disappears entirely until the for loop has concluded before doing the final flip as the second image. I'm looking to have it flip continuously until the loop is finished.
I imagine this has something to do with closures and scope...
Javascript:
$(function() {
for (var i = 0; i < 10; i++) {
$('#test_flip')
.css('background-image', 'url("tower1.jpg")')
.transition({
rotateY: '90deg'
}, function() {
$('#test_flip')
.css('background-image', 'url("tower2.jpg")')
.transition({
rotateY: '180deg'
});
});
};
});
jsfiddle: http://jsfiddle.net/ce9b9aja/
The issue lies in the fact that the for loop calls .transition 10 times consecutively. The calls are queued in the jQuery queue (which is done behind the scenes by transit.js), but they are not queued in the order you're expecting.
Take the following example:
$(function () {
$('#test').transition({x:40}, function () {
$(this).transition({y:40});
})
$('#test').transition({scale:0.5}, function() {
$(this).transition({skewX:"50deg"});
});
});
#test {
width: 10em;
height: 10em;
background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ricostacruz.com/jquery.transit/jquery.transit.min.js"></script>
<div id="test"></div>
In this example, the first transition x:40 will be executed instantly because there is no queue. Despite the fact that it is executed instantly, since it is an animation, it will be using some form of setTimeout or setInterval and will not be completed in the transition method call. Consequently, the scale:0.5 transition will be called while the x:40 transition is still animating, which will put it in the queue it before y:40 is put in the queue.
Therefore, the queue order is
x:40 -> scale:0.5 -> y:40 -> skewX:50deg
Similarly, your code is producing the following queue:
rotateY:90deg -> ... -> rotateY:90deg -> rotateY:180deg -> ... -> rotateY:180deg
Thus your code's behavior. It rotates the image 90deg first, then it does it 9 more times, which doesn't change anything visually (hence the "pause"). Then it changes the image and rotates it 180deg and does that 9 more times also.
One solution could be to create a recursive function using the callback of the .transition function. An example is implemented below:
$(function() {
FlipMe($('#test_flip'), "http://i.imgur.com/tYYtwbi.jpg", "http://i.imgur.com/G4CvJpc.jpg", 10)
});
function FlipMe($el, image1, image2, times) {
$el.css('background-image', 'url("'+image1+'")')
.transition({rotateY: '90deg'}, function() {
$el.css('background-image', 'url("'+image2+'")')
.transition({rotateY: '180deg'}, function() {
if(times > 0) {
FlipMe($el, image2, image1, times - 1);
}
});
});
}
Updated fiddle here: http://jsfiddle.net/ce9b9aja/1/
The code above exclusively uses callback functions to dictate the order of events. When the first transition is completed, the callback function will "queue" the next transition, which will be executed instantly since nothing else will be in the queue. And so on.

animate christmas ornaments with Jquery ui effects

hi i am playing with jquery ui effects and trying to animate some christmas ornaments. the idea is that they would swing if you hover over them. and swing from the midpoint of the top of the image (the top of the string) like a real ornament and not just the whole image moving back and forth.
what i have so far is here:
http://jsfiddle.net/9ceeW/
its displaying on click, when i do it on hover they dont work as well or realistically.
this is my first foray into jquery animation and i am not really sure how to proceed next. any help would really be appreciated.
thanks!
You can use the plugin from
http://www.zachstronaut.com/posts/2009/02/17/animate-css-transforms-firefox-webkit.html
add a custom animation queue as in A non-nested animation sequence in jQuery?
and you end up with animated christmas balls at http://jsfiddle.net/gaby/9ceeW/8/
update
updated to allow multiple balls to animate at the same time.. http://jsfiddle.net/gaby/9ceeW/9/
Check out the jQuery Path plugin for animating elements along curves. See the author's demo page.
Not really my thing, but you need to add something like this:
$('#ball1').click(function () {
$(this).effect("bounce", { direction:'left', times:1, distance:60 }, 500);
$(this).effect("bounce", { direction:'left', times:1, distance:30 }, 750);
$(this).effect("bounce", { direction:'left', times:1, distance:15 }, 1000);
$(this).effect("bounce", { direction:'left', times:1, distance:5 }, 1250);
});
Updated fiddle: http://jsfiddle.net/N7qM9/

Categories