So I've been working in assembly for awhile and just came back to websites after quite some time and one of the questions that are still bothering me today is, why can't I change a class from one animation (open/slide into view animation) to the other (close/slide out of view animation)? I have been being required to set up four different class names to achieve this such as:
.open {
height: 50px;
animation: keyframe 1s forwards 1 0s;
}
.opened {
height: 50px;
}
.close {
height: 0;
animation: keyframe 1s reverse forwards 1 0s;
}
closed {
height: 0;
}
And then in my javascript I am forced to add the keyframe set a timeout and then change to the one without a keyframe otherwise if for say close is already happened and is left on without changing to a class without an animation and in javascript I make it go from close straight to open it will NOT do the open animation? So I've been having to do something like this in javascript:
if (window.pageYOffset == 0 && !elm.classList.contains("closed")) {
elm.className = "close";
setTimeout(() => {
elm.className = "closed";
}, 1000);
} else if (window.pageYOffset > 0 && !elm.classList.contains("opened")) {
elm.className = "open";
setTimeout(() => {
elm.className = "opened";
}, 1000);
}
What I'm wanting to do is this though:
if (window.pageYOffset == 0 && !elm.classList.contains("close")) {
elm.className = "close";
} else if (window.pageYOffset > 0 && !elm.classList.contains("open")) {
elm.className = "open";
}
But if you do that the browser, I am using is Google Chrome, will NOT switch and do the animation, and this brings me to the next part of my question what is the required timeout time in this case? It seems I have to at least have a timeout greater than 50ms for it to register the class switch and do the animations? How do I calculate the required time frame? I assume I am supposed to create an infinite loop on the after the remove class name portion and then once it is removed activate the second part of adding the other classname? I have to do this for example:
elm.className = "";
setTimeout(() => {
elm.className = "new_class"
}, 50);
This example is to show how I am being forced to at least remove the current "close" animation wait for timeout and then add the "open" animation but what I do not know is what is the required time frame for this timeout to be efficient? I have seen using anything less than 50ms will be unregistered and will not do the new animation.
Related
I'm developing a game engine in HTML5. Characters are div elements using an animated sprite for background. As sprite animation have fluid parameters and must be set by code, they can't be predefined in a static CSS definition, thus I use element.animate to set sprite animations to a given row at a given speed knowing my scales and frame counts.
// Applies the given frame and animation to the sprite
// Frame is an angle, clockwise direction: 0 = up, 1 = right, 2 = down, 3 = left
set_animation(frame, duration) {
const scale_x = this.settings.sprite.scale_x * this.settings.sprite.frames_x;
const pos_y = this.settings.sprite.scale_y * -frame;
// Cancel the existing animation
if(this.data_actors_self.anim) {
this.data_actors_self.anim.cancel();
this.data_actors_self.anim = null;
}
// Play the animation for this row or show the first frame if static
if(duration > 0) {
this.data_actors_self.anim = this.element.animate([
{
backgroundPosition: px([0, pos_y])
}, {
backgroundPosition: px([scale_x, pos_y])
}
], {
duration: duration * 1000,
direction: "normal",
easing: "steps(" + this.settings.sprite.frames_x + ")",
iterations: Infinity
});
this.data_actors_self.anim.play();
} else {
this.element.style.backgroundPosition = px([0, pos_y]);
}
}
Obviously that's a snippet from an actor class function: this.element is the div, this.settings is an object with parameters to be used who's names should make sense in this context, the px() function is a simple converter to turn arrays into pixel strings for HTML (eg: [0, 0] to "0px 0px").
The issue I'm having: While I can always run this function to set a new animation, I want the ability to change the speed of the animation without resetting it. It doesn't need to be a smooth transition, for all I care the new speed can be applied at the next iteration... I only want to avoid a visual snap or any kind of reset upon applying the change. Once an animation is set, I have no idea how to access and update its duration parameter. Does anyone have any suggestions?
When using console.log on this.data.anim I'm rightfully told it's an animation object. I tried using JSON.stringify to get more information but nothing relevant is printed. this.data.anim.duration returns undefined so the setting must be stored under some other property. Even if I know that property, I'd like to be sure web browsers will agree with me changing it like this.data.anim.options.duration = new_duration.
You can wait for the end of an iteration before changing the animation duration if that is what is required.
This snippet only sets an event listener for animationiteration event when you click the button to increase the speed.
function upthespeed() {
const div = document.querySelector('div');
div.addEventListener('animationiteration', function() {
div.style.animationDuration = '1s';
});
document.querySelector('button').style.display = 'none';
}
div {
width: 10vmin;
height: 10vmin;
background-color: magenta;
animation: move 10s linear infinite;
}
#keyframes move {
0% {
transform: translateX(50vw);
}
50% {
transform: translateX(0);
}
100% {
transform: translateX(50vw);
}
}
<div></div>
<button onclick="upthespeed()">Click me to increase the speed at the end of the next iteration (you may have to wait!)</button>
The value for the animation duration isn't in the Animation object itself but in the CSS animation-duration property for the Element: so this.data_actors_self.style.animationDuration = new_duration will do the job. It will however restart the animation if it is being played, but if I understand correctly that isn't a problem for you.
Edit: To change the animation's duration without restarting it, all you have to do is set the value of anim.startTime to what it was before. For example:
const startTime = anim.startTime;
this.data_actors_self.style.animationDuration = new_duration
anim.startTime = startTime;
I am attempting to play a video then have the div fade out to 0 opacity at sixty seconds before completion. The issue I'm having is that in removing of the animation on the div which allows the video to fade in at the beginning in effect switches off the div, (the video). What I want to achieve is a fadeout at 60 seconds. What I hope to achieve is remove id animation without affecting video playback, then add timecode which will fade out video / (div) 60 seconds before the end. I may not have not explained this very well see the JSfiddle.
var callOnce = true;
function aperture(){
if ((media.duration - media.currentTime) < 60)
if (callOnce) {
sync();
callOnce = false;
}
}
function sync(){
"use strict";
var media = document.getElementById("media");
media.classList.add("timecode");
media.classList.remove("animation");
}
setInterval(aperture, 100);
JSFiddle: https://jsfiddle.net/oytqq0jb/
Your time detection code is correct, but the way you're handling the animation is wrong. Here I show what sync() and its CSS animation should look like:
function sync () {
var video = document.querySelector('.video');
video.classList.add('anim-fade-out');
}
setTimeout(sync, 2000);
.video {
width: 160px;
height: 90px;
background: black;
}
#keyframes fade-out {
to {
opacity: 0;
}
}
.anim-fade-out {
animation: fade-out 1s forwards;
}
<div class="video"></div>
Add the animation only when you want to start the fade out, there's no need to mess with running/paused. Once you add the class, the forward keyword will keep the last state of the animation when it's done animating, which in this case is opacity: 0
I'm making a website which will let you update an SQL table, and I want to add some sort of feedback when a button is clicked. I have made an invisible button (opacity=0) which lies to the right of each row as a status. I made this JS fade() function to set the opacity to 1, then slowly bring it back to 0, so a message pops up then fades away.
function fade () {
var invis = document.getElementById("invis".concat(num.toString()));
if(invis.style.opacity > .990) {
invis.style.opacity = (invis.style.opacity) - .001;
setTimeout(fade, 50);
} else if(invis.style.opacity > 0) {
invis.style.opacity = (invis.style.opacity) - .05;
setTimeout(fade, 50);
}
}
The trouble is, since webpages are single-threaded, any other action will interrupt the animation and leave behind a half-faded status. So that's no good. So now I am trying to set up the invisible buttons to change class when a new row is updated. The new class looks like this:
.invisible_anim {
...
opacity: 0;
animation:trans 3000ms;
}
#keyframes trans {
0% {
opacity: 1;
}
50% {
opacity: 1;
}
This works fine, except it only works once. From here I cannot get the animation to play a second time. I have tried changing the class back to "invisible" then "invisible_anim" with no luck. I also can't use JQuery or Webkit. I'm wondering if there's some flag you can set for a button without actually clicking on it so I can reset the class when I need to? Or even some way to thread my JS function so I can stick with that.
If you would like to play the animation multiple times (see docs here: https://developer.mozilla.org/en-US/docs/Web/CSS/animation), if you would like to play it twice only.
so this:
.invisible_anim {
...
opacity: 0;
animation:trans 3000ms;
}
#keyframes trans {
0% {
opacity: 1;
}
50% {
opacity: 1;
}
would turn to
.invisible_anim {
...
opacity: 0;
animation:trans 3s 2 ;
}
#keyframes trans {
0% {
opacity: 1;
}
50% {
opacity: 1;
}
EDIT:
Apparently the requirements are different than what I thought. Instead the solution seems to be to key off the animation event located at https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations and then when that animation done do what you need to do: so in JS-only
var e = document.getElementById("watchme");
e.addEventListener("animationend", listener, false);
function listener(){
//do what you need to do here
}
Just be careful, the reason for this is that most browsers have different "animationend" events that fire at different times. So definitely will need to be tested in different browsers to make sure that the animation event is firing at the right time. There's a post at (https://css-tricks.com/controlling-css-animations-transitions-javascript/) that details some of the issues you might encounter.
Have you considered using the CSS property "transition"? JavaScript has an event listener called "transitionend" that can trigger when your transition has ended, which you can use to reset the button.
First set the area for your alert button with the id invis.
CSS:
#invis {
opacity: 1;
transition: opacity 3s;
}
Then in JavaScript, generate your button and its content, which will appear at opacity 1, then transition to opacity 0. Your addEventListener will trigger when the animation is done, remove the button and reset the opacity for the next trigger.
JavaScript:
var invis = getElementByID("invis");
function fade() {
var button = document.createElement("button");
invis.appendChild(button);
invis.style.opacity = ("0");
invis.addEventListener("transitionend", function(){
invis.removeChild(button);
invis.style.opacity = ("1");
});
}
You can add the fade() function to your EventListener for the user "click."
This is my first time answering on StackOverflow, I hope this helps!
You need to start transparent then show then hide:
#keyframes trans {
0% {
opacity: 0;
}
50% {
opacity: 1;
}
100% {
opacity: 0;
}
}
Then simply add your class (remove after the 3000ms time period)
I trying to make what appears to the user to be an image fader. A string of images fade into each other. All the solutions that I found were complex, and normally required an for every image. I've come up with what should be a simple solution. It's working 90% on Firefox/Chrome/IE11 on Windows. On Android Chrome it's having issues.
Basically my idea is, I have two divs, absolutely positioned, one on top of the other. Both start with a background, sized to cover. The top one fades out, revealing the bottom one, and at the end of the animation, the background-image of the top one (current hidden) is changed to image 3. After a pause, it fades back in, and the background-image of the bottom one is changed to image 4. This repeats indefinitely.
HTML:
<div class="slideshow" id="slideshow-top"></div>
<div class="slideshow" id="slideshow-bottom"></div>
CSS:
.slideshow {
display:block;
background-size:cover;
width: 100%;
height: 100%;
position:absolute;
top:0;
left:0;
}
#slideshow-top {
z-index:-5;
background-image:url(http://www.andymercer.net/wp-content/uploads/2013/12/slider-1.jpg);
}
#slideshow-bottom {
z-index:-10;
background-image:url(http://www.andymercer.net/wp-content/uploads/2013/12/slider-2.jpg);
}
Javascript:
var url_array = [
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-1.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-2.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-3.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-4.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-5.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-6.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-7.jpg',
'http://www.walldoze.com/images/full/2013/12/04/wallpapers-desktop-winter-nature-x-wallpaper-backgrounds-natureabstract-designs-interesting-hd-19045.jpg'
];
var count = 1;
setInterval(function() {
if (count%2) { // Fade In
jQuery('#slideshow-top').animate({opacity:0}, '200000', function() {
jQuery('#slideshow-top').css('background-image','url('+url_array[count]+')');
});
}
else { //Fade Out
jQuery('#slideshow-top').animate({opacity:1}, '200', function() {
jQuery('#slideshow-bottom').css('background-image','url('+url_array[count]+')');
});
}
count = (count == url_array.length-1 ? 0 : count + 1);
}, 2000);
http://jsfiddle.net/5eXy9/
As seen in the Fiddle above, this mostly works. However, it seems to ignore the length of the animation. Using .fadeOut has the same effect. I've tried going from 200 to 20000, and there doesn't seem to be a difference.
I'm not sure if this is tied into the other issue, which is that on Android (Galaxy S4, Chrome, Android 4.x), the animation doesn't occur at all. It simply changes images. Any ideas?
EDIT: Jan 10 - Timing problem is fixed, but the main issue (Android) is still unsolved. Any thoughts?
The interval keeps going, so when increasing the animation speed, you have increase the interval speed as well.
The way you've built this, you should always keep the speed of both animations equal to the interval, or if you need a delay, increase the interval compared to the animations so it at least has a higher number than the highest number used in the animations.
The reason changing the speed doesn't work at all for you, is because it should be integers, not strings, so you have to do
jQuery('#slideshow-top').animate({opacity:0}, 200000, function() {...
// ^^ no quotes
I would do something like this
var url_array = [
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-1.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-2.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-3.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-4.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-5.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-6.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-7.jpg',
'http://www.walldoze.com/images/full/2013/12/04/wallpapers-desktop-winter-nature-x-wallpaper-backgrounds-natureabstract-designs-interesting-hd-19045.jpg'];
var count = 1;
var speed = 2000,
delay = 1000;
$.each(url_array, function(source) { // preload
var img = new Image();
img.src = source;
});
setInterval(function () {
if (count % 2) { // Fade In
jQuery('#slideshow-top').animate({
opacity: 0
}, speed, function () {
jQuery('#slideshow-top').css('background-image', 'url(' + url_array[count] + ')');
});
} else { //Fade Out
jQuery('#slideshow-top').animate({
opacity: 1
}, speed, function () {
jQuery('#slideshow-bottom').css('background-image', 'url(' + url_array[count] + ')');
});
}
count = (count == url_array.length - 1 ? 0 : count + 1);
}, speed + delay);
FIDDLE
Basically I have a banner of images which are to scroll from left to right. I have it working fine with jQuery (code pasted below) however it can be very jittery and the client wants it smoother. So after some research the best way is to use CSS3 (probably should have started here). I haven't used much CSS3 other than the basics like border-radius so had to read up. After seeing some examples I was able to try out making the scroll however I couldn't get it to work with jQuery as well.
The intended effect:
scroll slowly from right to left 'forever'
when mouse is over it, it stops scrolling
I do this with the following jQuery:
$(document).ready(function() {
var $scrollMe = $('.ScrollMe');
$scrollMe.hover(stopBannerAnimation)
$scrollMe.mouseout(startBannerAnimation)
function stopBannerAnimation()
{
$(this).stop();
}
function startBannerAnimation()
{
/*if (Modernizr.csstransitions)
{
$scrollMe.css('left', '{xen:calc '{$scrollerWidth} * 100'}px');
}
else*/
{
$scrollMe.animate(
{left: -{$scrollerWidth}},
{xen:calc '{$scrollerWidth} * 60'},
'linear',
function(){
if ($(this).css('left') == '{$scrollerWidth}px')
{
$(this).css('left', 0);
startBannerAnimation();
}
}
);
}
}
startBannerAnimation();
$('.ScrollMe ol').clone().appendTo('.ScrollMe');
});
Can someone help me get this same functionality while using CSS3 to handle the actual scrolling so it is smoother (in theory)?
This is how I'd do it, using 5 seconds for the animation speed:
Step 1: write your CSS3 transition class
.ScrollMe{
-webkit-transition:left 5s ease; // here the animation is set on 5 seconds
-moz-transition:left 5s ease; // adjust to whatever value you want
-o-transition:left 5s ease;
transition:left 5s ease;}
}
Step 2: set up the jquery to toggle the left position
function DoAnimation () {
var $scrollMe = $('.ScrollMe');
if ($scrollMe.offset().left === 0) {
// I imagine you calculate $scrollerWidth elsewhere in your code??
$scrollMe.css('left', $scrollerWidth);
} else {
$scrollMe.css('left', 0);
}
setTimeout(function () {
if (LaunchAnimation === true) { DoAnimation(); }
}, 5000); // here also assuming 5 seconds; change as needed
}
Step 3: control animation start/stop
var LaunchAnimation = true;
$(document).ready(function() {
$('.ScrollMe').mouseover(function () {
//this stops the div from moving
if (LaunchAnimation === true) {
$(this).css('left', $(this).offset().left);
LaunchAnimation = false;
}
});
$('.ScrollMe').mouseleave(function() {
DoAnimation();
LaunchAnimation = true;
});
}
This way, you let the CSS rendering engine of the browser control the speed and movement of the div for smoothness and you use jquery only as the trigger mechanism.
Hope this helps.