How to animate DOM elements with JavaScript/CSS - javascript

I'm working on a chess game with some strategic visual overlays. One of them requires some light animation of pieces and squares, specifically, a slow and steady pulsing. My board is a with each being a single square. Pieces are shown by setting the background-image in CSS to an .svg of the piece it contains.
Can this be done in CSS? I'm using the latest browsers with no support for legacies, so I can use all the nifty CSS3 stuff. Another option I was thinking was to set the background-image of the board to an animated .gif of the piece pulsing. Would this work?
Are there any other ways to do this I haven't mentioned? I would like to avoid packages/frameworks, but I am using jQuery.
CLARIFICATION:
I want to make the chess piece kind of pulse (flash?) in place slowly for emphasis. I want it to be a slow, subtle, and consistent pulse that persists until another event turns it off.

It sounds like you're looking for CSS animations.
Take a look here: http://www.w3.org/TR/css3-animations
In particular you'll need the following timing functions:
animation-name, to specify the set of keyframes to use.
animation-duration, to specify the speed of the animation.
animation-iteration-count, to repeat the animation.
animation-direction, to alternate the direction of the animation.
And you'll need to create some keyframes, which let you specify what CSS properties are modified by the animation.
Also, you'll need vendor prefixes on everything, so you need to write -webkit-animation-name rather than animation-name (for example), and repeat everything for -moz and other vendors.
Here's an example for webkit that creates a pulsating opacity effect. You can experiment with the properties in the from and to sections to animate size, color, etc.
.chess-piece {
-webkit-animation-duration: 1s;
-webkit-animation-name: pulse;
-webkit-animation-iteration-count: infinite;
-webkit-animation-direction: alternate;
}
#-webkit-keyframes pulse {
from {
opacity: 0.5;
}
to {
opacity: 1;
}
}
JSFiddle example for webkit and moz

That is quite possible and easy to do. As I understand it, you want to make some kind of glowing animation of the active chess figure?
Here's how I would go implementing a solution: Create 2 pngs, one with the chess figure in its unflashy ordinary state and one with its fully illuminated state. Then use jQuery to change the opacity of the illuminated state from 0 to 100 and back to 0 again.You can send the jQuery "on animation finish" signals to achieve this. You can than just use some kind of simplified observer pattern to cancel the effect once an event occurs.

Related

Is there a fluid CSS height property for elements entering the DOM? Jank happens when using Semantic-UI-React Transitions

I am not sure if this is the proper place to ask this question; I considered Software Recommendations however I figured I'd give it a shot here first.
I am creating a PWA and with every iteration I'd really like to focus on making it look/feel like less janky and as smooth as possible. Well, like a native app.
So here is the problem—I am using transitions (animations) provided by Semantic-UI-React, and while it works beautifully when an element which is occupying its on space, I was wondering if there a practice or pattern which handles the behavior of adjacent DOM elements to one that is being animated?
I supplied a GIF below to illustrate what I mean. I suppose I could just move the animated elements out of the container of the form to prevent jank, but I wondered if there was a more elegant pattern or approach to this...
Merci!
Unfortunately, there is no particularly elegant approach to this.
Regarding the question in the title of your post, a common approach is to animate the height of the new elements. If you don't know the height of the elements, unfortunately animating from 0px to auto does not yet work but you can fudge it by animating max-height from 0px to a value slightly larger than the maximum size you expect the element to be.
But don't do that.
It will cause the browser to layout the page on every animation frame and will almost certainly jank on lower-end devices.
Instead, you're better off to animate transform.
The most common approach is to:
Grab the original position of the elements (using getBoundingClientRect() etc.) that are going to be affected just before you add the new elements to the DOM (perhaps using getSnapshotBeforeUpdate unless you're using hooks, in which case you can use useRef to similar effect).
After you've added the new elements (which you're presumably also animating in by using transform with a suitable scale() function), calculate the delta from where the offset elements are now, compared to where they used to be.
Setup a transform animation from the negative of the delta, to zero (i.e. the FLIP approach). E.g. if the element has been shifted 300px down the page, animate transform from translateY(-300px) to none.
Of course you need to do that for all the elements in the flow that are affected so it might be easiest to put them all in one container and just animate that.
Regarding the third point you have a few choices of technology, none of which are great:
CSS transitions. These are simplest but you'll have to trigger a style flush to get the negative delta starting point to stick. e.g.
elem.style.transform = `translateY(-${offset}px)`;
elem.style.transition = `transform .3s`;
getComputedStyle(elem).transform; // Flush style
elem.style.transform = `none`;
CSS animations. Producing #keyframes rules dynamically using the CSSOM is a pain but at least you don't need to trigger a style flush (and you can set an animation with an implicit to-keyframe for convenience).
#keyframes random-id { from: { translateY(-300px); } }
Web animations. This is probably the most well-suited.
elem.animate({ transform: [ `translateY(-${offset}px)`, 'none' ] }, 300);
// In future when browsers ship support for implicit to/from keyframes:
elem.animate({ transform: `translateY(-${offset}px)`, offset: 0 }, 300);
Unfortunately Safari only has Web Animations support in Tech Preview so Safari users will get the un-animated version until the next Safari release. Edge users will also get the un-animated version until the Chromium based Edge ships. There is a polyfill too but it's not actively maintained at this point in time.
If you're using React, Animating the Unanimatable is a helpful article on all this.
The other tricky part is making sure the scroll doesn't jump for which you might need to look into scroll anchoring.

CSS3 keyframes in JavaScript

Is it possible using animation keyframes in JavaScript? If your answer is no, please tell me how can I use codes like this?
I wrote my jQuery plugin but I don't know how can I use keyframes.
animate() doesn't work (translateZ...)
You first need to research css3 keyframes then maybe make a small example for yourself to get a basic understanding.
jQuery.Keyframes allows you to generate css3 keyframes and attach events on the fly with javascript.
Here is a third party library that allows for a variety of different translations.
http://ricostacruz.com/jquery.transit/
If that still doesnt so what you need you can refer to this question
Set Webkit Keyframes Values Using Javascript Variable
which will show you how to inject rules into the CSSOM dynamically using jQuery
Somewhat working fiddle for Firefox
uses
#keyframes rotate {
0% {-moz-transform: rotate(-10deg);}
100% {-moz-transform: rotate(-10deg);}
}
and other vendor prefix specifics. There seems to be some kind of problem where sometimes the animation will trigger but other times it wont. Haven t been able to figure out why

Continuous rotation animation using css3 or js?

I have some objects in an animation which are continously animating in a rotation back and forth using css3. To do this I have created a declaration like so:
#-webkit-keyframes wiggle {
0% {-webkit-transform:rotate(12deg);}
50% {-webkit-transform:rotate(-6deg);}
100% {-webkit-transform:rotate(12deg);}
}
And each object I want to use this for I do the following:
.p4, .p5, .p6 {
-webkit-animation-name: wiggle;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: ease-in-out;
}
Since I want some random between each of the objects I have the following altering animation durations:
.p4 {
-webkit-animation-duration: 5s;
}
.p5 {
-webkit-animation-duration: 7s;
}
.p6 {
-webkit-animation-duration: 8s;
}
And so on...
This works ok - (only testing in Chrome so far). But it doesn't seem to be very optimal.
I would like to know whether there is a faster way to achieve this. Or a leaner way. I believe I could perform this with JS but I'm not sure what is going to be more lightweight on the end users resources.
Is there a better way to achieve this sort of basic animation with less resources - and if so, how?
In addition to this, if I were to create this same animation using jquery for example, how could I actually test the memory usage required? I found something recently to test memory usage of tabs but it appears the results are inconsistent. ie sometimes 1 tab is using more memory than the other and vice versa even though the code remains the same.
Thanks for any pointers.
Stick with the CSS3 animations if they work as intended, and if needed do something in JS as a fallback for non supporting browsers.
Replacing the CSS3 with JS is not really leaner or less resource intensive, quite the opposite as CSS3 seems to have smoother animations and in some browsers will use hardware accelaration and the GPU, something not possible with JS (at least not easily).
All in all you'll end up writing more in JS, and perhaps use a library or plugin for rotating animations as well. It will be less smooth in most browsers, and use more resources as well as JS will have to set the css tranform values several times each second for a somewhat smooth animation.

Slow jQuery animation on iPad2

I'm currently building iPad-optimised website. I have some chunks of text that I should show/hide when user touches appropriate button. The text is inside of < p> tag. I use jQuery for toggling the visibility of the text:
$("my selector").toggle("fast");
But it is really choppy ... Is there some iOS specific way to do the animation, maybe another framework or something else ?
I don't think it should be that slow ...
There are several animation scripts that targets iOS, but the basics are that you should use CSS animations instead, and more specifically the translate3d property (for positioning) that triggers the iOS hardware.
For toggling opacity, you can use a regular -webkit-transition and toggleClass, f.ex:
p { -webkit-transition: opacity 0.2s linear; opacity:1 }
p.hide { opacity:0 }
and then:
$("my selector").toggleClass('hide');
I made a simple demo for you here: http://jsfiddle.net/rQFZd/
You can detect touch devices and serve css animation specifically to those that supports (and prefers) it.
EDIT: example of animating height: http://jsfiddle.net/rQFZd/1/. I’m not sure about iOS performance though, but I think it should be better than jQuery.
You can also add another container and then use translate3d to reposition the element instead of shrinking it, that should most certainly be smoother on iOS. Example: http://jsfiddle.net/rQFZd/2/

Transparent background progress bar?

I'm trying to find an animated progress bar with a transparent background. I would prefer to achieve it using JQuery, Javascript and/or CSS. Is this possible? I'd like something much like this: http://www.fcm.travel/progress_bar.gif Has anyone come across such a thing?
The other questions I've seen on here show static bars, nothing animated much like the example.
You can make anything transparent with CSS. The following makes 75% opacity (25% transparent)
style="opacity: .75; filter: alpha(opacity=75)"
(The extra filter rule is for IE)
Edit: If you care that it works as often as possible on older browsers, you would add the old -webkit- and -moz- rules
style="opacity: .75; filter: alpha(opacity=75); -moz-opacity: .75; -webkit-opacity: .75"
In the event the browser does not support opacity settings, it would automatically default back to 100% opacity which is not transparent or translucent at all
I'm not sure what you mean by transparent, but jquery ui has a progress bar: http://jqueryui.com/demos/progressbar/#animated
Technically, Animated PNG would be neat for this. However the support for it isn't really that wide last time I checked.
So what you could do, seeing you are open for JavaScript solutions, is create a spritemap image based on 24 bit PNG's so it has nice transparancy, that contains every state for the animation. Then with JavaScript and a decent enough timer/interval, simply change the background position for the image so it looks like it's showing a live animation.
I've just made something that would interest You few days ago, take a look at this progress bar

Categories