Changing CSS keyframes through Javascript - javascript

I would like to know whether it is possible to adjust the contents of CSS keyframes, as I have seen a variety of suggestions online but none of them seem to work for me.
These are the keyframes I have:
#keyframes changeColor {
0% {
color: yellow;
}
50% {
color: red;
}
}
#-moz-keyframes changeColor {
0% {
color: yellow;
}
50% {
color: red;
}
}
#-webkit-keyframes changeColor {
0% {
color: yellow;
}
50% {
color: red;
}
}
#-o-keyframes changeColor {
0%{
color: yellow;
}
50% {
color: red;
}
}
I would like to be able to adjust the color attribute for each one of the above keyframes through Javascript, so that the colours can be changed according to the value passed through Javascript. Is this possible in any way?
Thank you

Animating KeyFrame using jQuery is possbile using jQuery.Keyframes
var supportedFlag = $.keyframe.isSupported();
$.keyframe.define([{
name: 'roll-clockwise',
'0%': {
'color' : 'green'
},
'100%': {
'color' : 'yellow'
}
}
]);
$("p").playKeyframe({
name: 'changeColor',
duration: 2000
});
For more info please see this link.
https://github.com/Keyframes/jQuery.Keyframes

This might work better entirely in Javascript, with the only consistent CSS attribute that should always be on the element a transition attribute: transition: color 0.5s ease-out for example.
Then in javascript you could have a setInterval alternate between colors somehow:
// Note that this is psuedocode and will need to be refactored slightly to better fit your own code
// variables storing color values
var colorA = 'red',
colorB = 'blue';
//store element you are changing in a variable
const ELEMENT = document.querySelector('element');
function changeColors() {
// store current color value of ELEMENT in a variable called currentColor
let currentColor = ELEMENT.style.color;
// if color is currently A, switch to B
if (currentColor == colorA) {
ELEMENT.style.color = colorB;
}
// else, switch to A
else {
ELEMENT.style.color = colorA;
}
}
// call set interval to alternate colors with same timing value as set in transition attribute in CSS
setInterval(changeColors, 500);
That's just one way it could be done in javascript, but the main takeaway here is that, at the end of the day, it's probably a lot more feasible to do it all in javascript rather than with CSS animations.

Related

How to animate or use transitions on a message pop up with javascript and css?

I currently have the message displaying and disappearing as I want but the transition isn't working, This is what I tried.
const alertMsg = document.querySelector('.alert');
contactForm.addEventListener('submit', formSubmitted);
function formSubmitted(e) {
//other stuff
alertMsg.style.display = 'block';
setTimeout(() => {
alertMsg.style.display = 'none';
}, 5000);
}
.alert {
transition: all 0.5s ease-out;
}
<div class="alert">Your message has been sent, I will get back to you as soon as possible.</div>
The message just instantly disappears and reappears, how can I use the transition currently to make some sort of animation?
This is my first question so sorry if I missed any information out, I will add any more if needed. Thanks
You can't transition (or animate) the display property. the display property is either on or off there's nothing to transition or animate.
What you can do is animate opacity and alter the display property at start and end.
something like:
#keyframes showBlock {
from { display: block; opacity: 0; }
to { opacity: 1; }
}
#keyframes hideBlock {
from { opacity: 1; }
to { opacity: 0; display: none; }
}

How to trigger a CSS animation?

I am stuck trying to trigger a CSS animation.
My CSS:
h3[id="balance-desktop"]{
color: black;
-webkit-animation-name: gogreen;
-webkit-animation-duration: 2s;
animation-name: gogreen;
animation-duration: 2s
}
/* Safari 4.0 - 8.0 */
#-webkit-keyframes gogreen {
from {color: black;}
to {color: limegreen;}
from{color: limegreen;}
to{color: black;}
}
/* Standard syntax */
#keyframes gogreen {
from {color: black;}
to {color: limegreen;}
from{color: limegreen;}
to{color: black;}
}
It is a basic animation that changes color of a h3[id=balance-desktop] element.
The animation works when the page loads. I am trying to get it to work when I call my java script function but I am unable too.
Attempt #1:
function showGreenAmiamtion(){
var test = document.getElementById("balance-desktop");
test.style.webkitAnimationName = 'gogreen';
test.style.webkitAnimationDuration = '4s';
}
Attempt #2:
function showGreenAmiamtion(){
document.getElementById("balance-desktop").style.webkitAnimationName = "";
setTimeout(function ()
{
document.getElementById("balance-desktop").style.webkitAnimationName = "gogreen";
}, 0);
}
I tried all answers from How to activate a CSS3 (webkit) animation using javascript?, no luck.
Is something wrong with my code?
Your attempt 2 works - just cleaned up your code a bit to remove the webkit prefixes (which are a few years outdated). I'm setting the animationName to 'none' inline, and then removing that so the element goes back to using its original CSS animation name.
Also, having multiple from and tos in a keyframe animation won't work, so I formatted it to work with percentages.
var btn = document.getElementById("button");
var text = document.getElementById("balance-desktop");
function turngreen() {
text.style.animationName = 'none';
setTimeout(function() {
text.style.animationName = null;
}, 0);
}
btn.addEventListener('click', turngreen);
#balance-desktop {
color: black;
animation: gogreen 2s;
}
#keyframes gogreen {
0%, 100% { color: black; }
50% { color: limegreen; }
}
<h3 id="balance-desktop">Heading</h3>
<button id="button">Turn Green</button>
For something like this, a CSS Transition might be more simple.
Also, all major browsers support CSS3 Animations and Transitions these days, so unless you are targeting old browsers, you can drop the vendor prefixes.
// Get DOM references:
var btn = document.querySelector("button");
var h3 = document.querySelector(".balance-desktop");
// Set up trigger for transition function. This is a button
// click in this example, but the function can be called anytime
// you like.
btn.addEventListener("click", function(){
// By changing a style property on the element that had previously
// been set, and if that element has been set up for transitions
// on that property, the transition will be activated.
h3.classList.add("goGreen");
// After the transition to the new style is complete
// we'll remove that style, effectively causing a
// transition back to the original style. It's important
// that the delay is set to at least the time of the transition.
// Two seconds in this case.
setTimeout(function(){
h3.classList.remove("goGreen");
},2000);
});
.balance-desktop{
color: black;
/* Set the element to transition on all properties
that have been set over the course of 2 seconds. */
transition:2s all;
}
.goGreen {
color: limegreen;
}
<h3 class="balance-desktop">Hello</h3>
<button>Run Function</button>

Is it possible to restore an element to it's previous position without passing the position as a parameter?

The following function takes an options parameter and animates the element to a particular amount of pixels based on a startValue:
options: {
property: 'right',
startValue: '-250px',
amount: '250px'
},
function (options) {
const $el = $(this.el)
$el.click(() => {
const startValue = $el.parent().css(slide.property)
const calcValue = parseInt(startValue, 10) + parseInt(slide.amount, 10)
if (startValue === slide.startValue) {
$el.parent().animate({ [slide.property]: calcValue }, 200)
} else {
$el.parent().animate({ [slide.property]: slide.startValue }, 200)
}
})
}
But I'm wondering, is it possible to accomplish the same without having to provide the startValue to the function? (e.g if the initial value of right was 0 then restore it to 0 the second time you click the element.)
You can take advantage of the fact that .animate() is adding an inline style attribute when it is called. So if you want to restore an element back to the right value specified in your CSS, you can call .removeAttr("style"). To get the animated effect, you would have to include a transition property in your CSS.
For example, check out this working fiddle: https://jsfiddle.net/hr0cxax2/1/
$("#slideButton").on("click", function() {
$("div").animate({right:"-=50px"}, 200);
});
$("#restoreButton").on("click", function() {
$("div").removeAttr("style");
});
div {
height: 50px;
width: 50px;
top: 20px;
right: 300px;
background-color: red;
position: fixed;
-webkit-transition: right 0.2s;
-moz-transition: right 0.2s;
transition: right 0.2s;
}
Otherwise, as far as I know, you would need to get and save the original right value before .animate() is called.

CSS or JS transition for button that changes size from text changes?

I have an Angular app with a button that has a label of "+"
On mouse-over I call element.append(' Add a New Number'); This adds that text new to the + in the label.
Use clicks the button, new number is added, label of button is returned to "+"
I would like to animate the button size change and/or the txt label change. So far, just adding a css transition to width does nothing.
Thoughts?
UPDATE:
To help clarify, this is a bootstrap input group button. I don't want to set widths or css transforms, to avoid breaking the group either here or at other screen sizes.
here are the 2 states:
I was simply letting the existing button stretch due to the injection of more words.
I am probably guessing you don't have a predefined width. anyways you could use transform-origin and scale to achieve such an effect
FIDDLE HERE
HTML:
<button id="btn">Click</button>
CSS:
#btn {
outline: none;
border:none;
background: orange;
padding: 1em 1.5em;
-webkit-transition: .3s;
-o-transition: .3s;
transition: .3s;
}
#btn:hover {
-webkit-transform: scaleX(1.2);
-ms-transform: scaleX(1.2);
-o-transform: scaleX(1.2);
transform: scaleX(1.2);
-webkit-transform-origin:0 0;
-moz-transform-origin:0 0;
-ms-transform-origin:0 0;
-o-transform-origin:0 0;
transform-origin:0 0;
}
you should use CSS transforms for animations rather than a property like width. The animation is slightly jerky , so you might want to work on it a bit more.
You had jQuery tagged, so this is how I would do it.
All the transitions. fade + animate
function changeButtonText(button, text){
// jQuery it
$button = $(button);
// get orinal css'es
oooon = $button.css('text-align');
doooo = $button.css('overflow');
treee = $button.css('white-space');
$button.css('text-align', 'left').css('overflow', 'hidden').css('white-space', 'nowrap');;
// get new width first
$tmpBtn = $button.clone().append(text).css('opacity', '0.0').appendTo('body');
newWidth = $tmpBtn.outerWidth();
$tmpBtn.remove();
// now stretch the button out
$button.animate({width: newWidth+"px"});
// fade texts into the butt
$button.append('<span style="display:none">'+text+'</span>');
$btnText = $button.find('span').fadeIn('slow');
return {
'text-align':oooon,
'overflow':doooo,
'white-space':treee
};
}
Fiddle
I think that with bootstrap CSS and Angular - it will be more complex, but this is how I would go about it programatically. You'll have to deal with the model and the data differently - and you should probably build a directive to repeat the action and integrate with Angular smoothly:
HTML
<div class="thing">+ <span id="message">
<span id='target'></span>
</span></div>
JavaScript
$('.thing').hover( function() {
var originalWidth = $(this).outerWidth();
$messageHolder = $(this).find('#message');
$target = $(this).find('#target');
$target.text('Some helpful text');
var targetWidth = $target.outerWidth();
$messageHolder.animate({
width: targetWidth
}, {
duration: 200,
complete: function() {
$messageHolder.animate({
opacity: 1
}, 500);
}
});
});
$('.thing').on('click', function() {
$target = $(this).find('#target');
$target.empty();
$messageHolder = $(this).find('#message');
$messageHolder.animate({
opacity: 0
}, {
duration: 200,
complete: function() {
$messageHolder.animate({
width: 0
}, 200);
}
});
});
I'm sure that Angular's ng-animate library watches the dom and also has an excellent way of animating things as they change in the model/controller or whatever they are calling it. This is probably something what it looks like behind the scenes.
Good luck!
jsFiddle

Change button background image, text and shape on hover at the same time

I am wondering if it is possible to make a button background image or text change to another text or image along with the button shape on mouse hover?
Say I had a button having a certain text or background image shoving the symbol ✓ (checkmark) and I wish it to change shape (from a circle to a rectangle) and text (from checkmark to the word submit) on mouse hover.
Is it possible using CSS, JS or both?
Without Changing Animations
JSFiddle
If you just want to change the background image and shape, you can use pure CSS
.button {
height:30px;
width:60px;
-webkit-border-radius:15px;
-moz-border-radius:15px;
border-radius:15px;
background-image:url(...)
}
.button:hover {
-webkit-border-radius:0px;
-moz-border-radius:0px;
border-radius:0px;
background-image:url(...)
}
If you want to change the text, you need JavaScript.
<style>
#button {
height:30px;
width:60px;
border-radius:15px;
background-image:url(img1.png);
}
</style>
<script>
function mouseOver() {
document.getElementById("button").style.backgroundImage = "url(img2.png)";
document.getElementById("button").style.borderRadius = "0px";
document.getElementById("button").innerHTML = "Submit";
}
function mouseOut() {
document.getElementById("button").style.backgroundImage = "url(img1.png)";
document.getElementById("button").style.borderRadius = "15px";
document.getElementById("button").innerHTML = "✓";
}
</script>
<div id="button" onmouseover="mouseOver()" onmouseout="mouseOut()">✓</div>
With Changing Animations
JSFiddle
To animate the button, use the
-webkit-transition:all 0.2s;
transition:all 0.2s;
functions. Every property that is changed in the :hover css, is automatically animated with a duration of 0.2 seconds.
If you also want the text to change (in my example fading in and out) it gets a little more complicated. (Disclaimer: My solution is probably not the most elegant one, but it works.)
Add two more classes to your CSS, .fade-out and .fade-in.
.fade-out {
opacity: 1;
animation: fadeOut 0.2s;
}
.fade-in {
opacity: 0;
animation: fadeIn 0.2s;
}
In this case I wanted the text animation to be a little longer than the border animation (I think it looks better), but if they should be the same length, you have to set each of the animations to 0.1s
Then add two #keyframes animations, fadeOut and fadeIn like this:
#keyframes fadeOut {
from {opacity: 1;}
to {opacity: 0;}
}
#keyframes fadeIn {
from {opacity: 0;}
to {opacity: 1;}
}
Now the tricky part, the JavaScript:
function mouseIsOver() {
btn = document.getElementById("button_java");
btn.childNodes[0].className += ' fade-out';
setTimeout(function(){
btn.childNodes[0].innerHTML = "Submit";
btn.childNodes[0].className = btn.childNodes[0].className.replace(' fade-out', '');
btn.childNodes[0].className += ' fade-in';
setTimeout(function(){
btn.childNodes[0].className = btn.childNodes[0].className.replace(' fade-in', '');
}, 200);
}, 200);
}
function mouseIsOut() {
btn = document.getElementById("button_java");
btn.childNodes[0].className += ' fade-out';
setTimeout(function(){
btn.childNodes[0].innerHTML = "✓";
btn.childNodes[0].className = btn.childNodes[0].className.replace(' fade-out', '');
btn.childNodes[0].className += ' fade-in';
setTimeout(function(){
btn.childNodes[0].className = btn.childNodes[0].className.replace(' fade-in', '');
}, 200);
}, 200);
}
childNodes[0] gets all inner children (tags), and chooses the first one
className += ' fade-out' adds the class 'fade-out' to the elements class list. There needs to be a space in front of the added class name, just so if there are classes already defined, they won't combine into one non-existent class
setTimeout(function,waitduration) runs the code in function after it waitet waitduration milliseconds. Match this length to the duration of your animation in the .fade-out{...} class in your CSS-file
className.replace(' fade-out','') replaces the fade-out class in the elements list of classes with an empty string to remove it. Don't forget to remove the space, too.
Your Personalized Button
JSFiddle or PasteBin
I've copied the code from your page, added a <p> wrap around the text in the button, and added
.button p {
line-height:1em;
margin:0;
}
to the CSS.
Then you need to import jQuery by adding
<script src="http://code.jquery.com/jquery-2.1.3.js"></script>
into the head. Then add another code snippet,
<script type="text/javascript">
$( document ).ready(function() {
$("#subscribe_button").hover(
function() {
txt = $("#subscribe_button").children("p");
txt.fadeOut(100, function() {
txt.html("Sottoscrivi");
txt.fadeIn();
});
}, function() {
txt = $("#subscribe_button").children("p");
txt.stop(true,false).fadeOut(100, function() {
txt.html("✓");
txt.fadeIn();
});
}
);
});
</script>
That should be it!

Categories

Resources