generate #-webkit-keyframes CSS dynamically with JavaScript? - javascript

I can produce
-webkit-animation-name:mymove;
dynamically with
object.style.animationName="mymove"
but is it possible to generate something like
#keyframes mymove
{
from {left:0px;}
to {left:200px;}
}
dynamically with JS?

Yes, i use Jquery library and then apply like so:
Say in this situation i want the left value to be dynamic from a div with attribute class value = "push"
<!--HTML-->
<div class="push">Wall</div>
//--JS--
var KeyFrame =
{
init: function(){
if(!KeyFrame.check)
{
//get the left position
var pushLeft = $('.push').position().left;
//set the style and append to head
var css = $('<style>#keyframes mymove{from {left:0px;}to {left:'+pushLeft+'px;}}</style>').appendTo('head'); //make sure you don't carriage return the css inline statement, or else it'll be error as ILLEGAL
//so u don't keep appending style to head
KeyFrame.check = true;
}
}
}
KeyFrame.init();

Consider the idea of how to access the styleSheet...
document.styleSheets[0].insertRule(animationRule)
It's certainly going to be complicated to do well, so briefly you'd want to retain a link and alter the rule associated with each object or something to avoid clutter. Or you could try to run a form of garbage collection with time stamps or something to figure out when the old ones can be removed.
From a quick look for other links I found...
http://davidwalsh.name/add-rules-stylesheets
deleteRule
http://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/deleteRule
insertRule (addRule precedes and is therefore more reliable)
http://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet.insertRule
I'm also just now noting something else that might be useful...
http://developer.mozilla.org/en-US/docs/Web/API/CSSKeyframesRule
Actually this looks like a better cleaner understanding or at least another way.
http://blog.joelambert.co.uk/2011/09/07/accessing-modifying-css3-animations-with-javascript/

Okay so if I am understanding correctly this jsfiddle should do the trick.
It uses a pre-defined set of transition properties, and changes the values dynamically via jquery.
The syntax for defining these animations is as follows...
transition-property: prop1, prop2, prop3;
transition-duration: timing1, timing2, timing3;
transition-timing-function: ease1, ease2, ease3;
By doing this, you can achieve nearly everything you can with #keyframes (not quite everything, but certainly a fair amount), it just happens to be built into the element style. From here you can go on to change whatever you want via jquery. If its the amount to move you can doing something like...
$("#myElem").css("left", "50px");
and the css3 transition will take care of the rest. If it's something like changing the ease type you can do that too with...
$("#myElem").css("transition-timing-function", "linear");
I know this is not exactly what you were looking for, but chances are it will do the trick.

It looks as if you have an understanding of css3 keyframes. I recommend jQuery.Keyframes to generate keyframes, you can also attach events and callbacks to the animations.

Yes you can, when you write your javascript code, you use the setAttribute() function vs the style() so that you can include more than one type of style. Just insert the animation-name, animation-duration, animation-timing-function or any other types that you wish.
<!DOCTYPE html>
<html>
<head>
<title> Welcome </title>
<meta charset = "utf-8">
<style>
#keyframes appear-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
#landing-page {
width: 100%;
height: 1000px;
}
</style>
<script>
window.addEventListener('load', function(){setTimeout(renderService, 1000)});
function renderService(){
var server = document.getElementById('Services');
server.setAttribute("style", "animation-name: appear-in; animation-duration: 5s; animation-timing-function: ease-in; background-image: url('https://wallpaperaccess.com/full/949819.jpg'); background-size: 80% 100%; background-position: center");
}
</script>
</head>
<body>
<div id = "landing-page">
</div>
</body>
</html>

Related

Apply a animation to an HTML Tag with Javascript on Clickevent

:D
I got akey frame and i want to apply the animation it to the body when button is clicked
document.getElementById('button2').addEventListener('click', infos2)
function infos2 () {
document.getElementsByTagName("body").style = "body{animation:rotate-scale-up .2s linear infinite both}";
}
well my JS dosent work obviously :D Any Idea?
Welcome to Stackoverflow.
The problem here is that the style you apply here is invalid.
Your style should be applied like this:
document.getElementsByTagName("body")[0].style.animation = "rotate-scale-up .2s linear infinite both";
getElementsByTagName returns an array of objects, therefore you have to insert [0] to select the first element in that array to make it work correctly.
You can also use document.body instead.
If you apply a style directly on a HtmlObject like the body, the style will expicitly be set on this element. You don't need a 'body' selector in this case.
Plus: You need an imported stylesheet or a style tag in the page, where the animation-keyframes of rotate-scale-up are defined. It's not obvious if you already done that or not.
Something like:
<style>
#keyframes rotate-scale-up{
0% { transform: scale(.1) rotate(0deg)}
100% { transform: scale(1) rotate(360deg)}
}
</style>
Otherwise you page will not know what rotate-scale-up is.

Animating a Variable Font using Javascript

I'm trying to animate a variable font's axis in Javascript, the axis is called 'FLUX' and it affects a vertical movement in the variable font. I got this part to work in CSS, however I would also like for the second axis, the 'wdth', to correspond to the viewport width. I got this to work in too, but in Javascript.
Now the issue is that both won't work simultaneously. I feel like the way to get this to work is to animate both axes in Javascript, however I cannot figure out how to achieve the 'FLUX' animation in Javascript, only CSS.
I've included a Codepen link to what I've been working on, you can see the Javascript works when the CSS animation is disabled, but with it enabled the CSS seems to override the Javascript.
https://codepen.io/Xenitos/pen/YMbboX
HTML
<html>
<head>
<meta charset="UTF-8" />
<title>Test Responsive Width</title>
<body>
<div class="rapper">
<h1 id="title">Flux</h1>
</div>
</body>
</html>
CSS
body{
padding: 0;
margin: 0;
}
.rapper{
padding: 20px;
}
#title{
font-size: 20vw;
color: black;
font-family:"Flux";
text-transform:uppercase;
font-variation-settings: 'wdth' 400;
animation: title infinite;
animation-duration: 15s;
animation-timing-function: ease;
}
#keyframes title {
0% {font-variation-settings:"FLUX" 400 ; }
50% {font-variation-settings:"FLUX" 700 ; }
100% {font-variation-settings:"FLUX" 400 ;}
}
JAVASCRIPT
$( document ).ready(function() {
// Variables
var $window = $(window);
$window.resize(function(){
$('#title').css('fontVariationSettings', "'wdth'" + ($window.width()-450)*100/(1920-450)*4);
})
});
// End temp code for seeing browser width
The expected result is that the viewwidth is linked to the 'wdth' axis of the font and the 'FLUX' axis is animated on a infinitely on a loop.
Is there something I'm missing, or could someone please help me accomplish this entirely in Javascript?
The problem is that font-variation-settings will reset every axis that is not explicitly set.
For instance, in your CSS you set font-variation-settings: 'wdth' 400; and an animation that changes font-variation-settings: "FLUX" 400;. You would expect these would combine, but alas: the animation does not contain a value wdth so that will immediately be reset to its default value once the animation starts.
Likewise with the JavaScript part: CSS and JavaScript are fighting to set font-variation-settings, each undoing the other's settings.
So, at every step it's important to set both the values.
(Tip to get JavaScript and CSS to work together: instead of writing directly to font-variation-settings from JavaScript, write to a CSS variable and use that in the CSS/animation.)
I think you are modifying the wrong variation setting in the #keyframes steps
#keyframes title {
0% {font-variation-settings:"wdth" 400 ; }
50% {font-variation-settings:"wdth" 700 ; }
100% {font-variation-settings:"wdth" 400 ;}
}

Animation dependent on previous page (via link)

I'm very new to JavaScript and I'm trying to figure out a way to trigger a keyframe animation if the page is accessed via a link on a menu page.
The code I have come up with so far using document.referrer does not work:
var ref = document.referrer;
if (ref.includes("menu")) {
document.getElementById('symbol').style.animation=' 2s ease-in-out 0s 1 slideLogo';
}
What am I doing wrong? The script is located at the end of <body> and runs nicely when ref is changed to a statement containing the search word.
I'm currently only testing locally, could that be why?
Hard to say what is going wrong without seeing the rest of the code, but the following should work.
Save as landing.html
<style type="text/css">
#symbol {
width: 100px;
height: 100px;
background-color: red;
}
#keyframes slideLogo { from { margin-left: -20%; } to { margin-left: 100%; } }
</style>
<h1>Landing page</h1>
<div id="symbol"></div>
<script>
var ref = document.referrer;
console.log('referrer is', ref);
if (ref.includes("menu")) {
console.log('set the style.animation property');
document.getElementById('symbol').style.animation=' 2s ease-in-out 0s 1 slideLogo';
}
else {
console.log('DO NOT set the style.animation property');
}
</script>
Put a link to landing.html in a file called menu.html. And make sure you're accessing it via something like http://localhost/menu.html
Similarly, put a link to landing.html in a file that will not have "menu" anywhere in the url, e.g.http://localhost/something-else.html. This will not trigger the animation.
So if these 3 files are accessed by their filenames, then the link from http://localhost/menu.html will trigger the animation on http://localhost/landing.html
It's worth noting that your referrer test will look anywhere in the referrer url, so even partial matches like http://localhost/not-a-menu.html will trigger the animation. So you may want to make your test a little more specific if you're worried about this.
Also, for browser compatibility, I think at this point it is still a little safer to use indexOf instead of includes.
if(document.referrer.indexOf('menu') !== -1) { ... }

Is it better for performance to dynamically change transition in JS directly, or using css classes instead?

I have two elements that do a simple intro animation when scrolling. And I want to reverse the transition speed when going back.
Both these approaches work, but the site is kinda laggy so I was wondering which one is better for performance. Doing it in javascript like this..
function startAnimation(){
elem1.classList.add('transformClass');
elem2.classList.add('transformClass');
elem1.style.transition = 'transform 0.6s';
elem2.style.transition = 'transform 1.4s';
}
function exitAnimation(){
elem1.classList.remove('transformClass');
elem2.classList.remove('transformClass');
elem1.style.transition = 'transform 1.4s'; //elem1 is now 1.4s instead of 0.6s
elem2.style.transition = 'transform 0.6s';
}
or would it better to incorporate the transition into the added classes and using !important
function startAnimation(){
elem1.classList.add('transformClass1');
elem2.classList.add('transformClass2');
}
function exitAnimation(){
elem1.classList.remove('transformClass1');
elem2.classList.remove('transformClass2');
}
//CSS:
#elem1 {
transition: transform 0.6s
}
#elem2 {
transition: transform 1.4s
}
.transformClass1 {
transition: transform 1.4s !important;
}
.transformClass2 {
transition: transform 0.6s !important;
}
There're some conditions in this test that I've done with your code.
There's no HTML codes given to me - I had to make my own HTML codes, which means, this result might not be the one from the same source.
The website I've used to test JavaScript codes does not support to make an external CSS file, which means, I had to put <style></style> tag with HTML, so it might be different from adding an external CSS file.
The number of executing each codes is about 3,000.
[Related to #2] Since I had to put <style></style> in HTML, that means, the codes that is consist of only JavaScript couldn't be run with the codes consist of JavaScript and CSS, together, because as I mentioned <style> tag, it affects both. So I had to run them separately.
Here's HTML I made:
<div id="elem1"></div>
<div id="elem2"></div>
<div class="transformClass1"></div>
<div class="transformClass2"></div>
And here's the result I've got:
Gray - Only JavaScript
Green - JavaScript + CSS
Lower is better
※ Website I've used - http://jindo.dev.naver.com/jsMatch
made by Naver, from South Korea

FadeIn animation using CSS3 in Javascript

As jQuery.fadeIn is not very smooth on mobile devices I try to use CSS but it doesn't work as expected. How to create a smooth CSS animation using Javascript?
In general this is what I'm trying:
$('div')
.css('opacity', 0) // at first, set it transparent
.css('display', 'block') // make it appear
.css('transition', 'opacity 1000ms linear') // set a transition
.css('opacity', 1); // let it fade in
https://jsfiddle.net/8xa89y04/
EDIT1:
I'm not searching a solution using static CSS classes. The point is: I need to set this dynamically in Javascript code - a replacement for jQuerys fadeIn() for example.
Your logic isn't quite right. Firstly you cannot animate display, so to achieve what you require the element has to always be rendered in the DOM (ie. anything but display: none). Secondly, the transition property should be placed within the CSS styling itself. Finally you can make this much more simple by setting all the rules in CSS classes and just turning the class on/off. Try this:
div {
position: absolute;
width: 100px;
height: 100px;
background-color: black;
opacity: 0;
transition: opacity 1000ms linear;
}
.foo {
opacity: 1;
}
$('div').addClass('foo');
Working example
Use this code.
CSS
div {
width: 100px;
height: 100px;
background-color: black;
transition:opacity 2s;
}
JavaScript
$('div').hover(function(){
$(this).css('opacity','0');
})
Without using CSS properly, you are going the long way about it. You'll need to emulate what you would normally do in CSS, using JavaScript, so you'll be setting all your CSS properties, transitions etc, then applying them with js.
I can't personally see any benefit in doing this. Using actual CSS would be cleaner, more efficient, more maintainable, and simply a plain better solution to what you need.
I think this is what you are looking for.
$('div').css({"display":"block", "opacity":"0"}) //Make div visible and opacity as "0"
$('div').animate({opacity :1}, 1000); //Animate div to opacity "1"
Take a look at this Demo
Found the cause here: CSS transitions do not work when assigned trough JavaScript
To give this attention I need to give the browser some time - or better: a working slot to activate the transition as the time seems not to be a problem.
The following code cuts the process in two by using setTimeout()... and it works!
var div = $('div');
// first process
div
.css('opacity', 0) // initial opacity
.css('display', 'block') // make it appear (but still transparent)
.css('transition', 'opacity 1s linear'); // set up a transition for opacity
// break - start the transition in a new "thread" by using setTimeout()
window.setTimeout(function(){
div.css('opacity', 1); // start fade in
}, 1); // on my desktop browser only 1ms is enough but this
// may depend on the device performance
// maybe we need a bigger timeout on mobile devices

Categories