I have problem.
I want to instantly fade out my square (after clicking a button) then afterwards, fade it in slowly with a delayed time.
This is my example fiddle:
http://jsfiddle.net/qFYL7/6/
I changed the class but i'm afraid it's not the proper approach:
my_square.className = 'dim_fast';
my_square.className = 'square';
Thanks for any help given!
Well, in your function you're changing the class to dim_fast and then immediately back to square, which has no transitions :)
So, remove:
my_square.className = 'square';
Or at least append the 2nd class:
my_square.className = 'square dim_fast';
To fade out the square, and then fade in after an amount of time, you can use setTimeout.
Example
HOW ABOUT A PURE CSS3 SOLUTION?
First you need to make sure that the button is positioned before the square.
<button id="bt1"> </button>
<div id="my_square" class="square"> </div>
This is because CSS doesn't have a "previous sibling" selector.
Now you must use the :active pseudo-element on the button, to directly hide the square.
#bt1:active + .square
{
-webkit-transition:opacity 0s;
-moz-transition:opacity 0s;
-o-transition:opacity 0s;
transition:opacity 0s;
opacity:0;
}
When you click the button, the square will instantly be hidden.
Now add the transition on the square.
.square
{
-webkit-transition:opacity 2s;
-moz-transition:opacity 2s;
-o-transition:opacity 2s;
transition:opacity 2s;
opacity:1;
}
The Square will Fade In in 2 seconds.
CHECK IT OUT
I would use animation for this instead of transitions
Altered CSS (from your jsfiddle)
.square
{
width:100px;
height:100px;
background-color:blue;
opacity:1;
}
.fade{
animation: dim_fast_shine_slow 1s;
}
#keyframes dim_fast_shine_slow{
99%{opacity:0;}
100%{opacity:1}
}
Altered script
var my_square = document.getElementById('my_square');
function dim_fast_shine_slow()
{
// remove class
my_square.className = my_square.className.replace(' fade','');
setTimeout(function(){
// add class after 50 millisecons to allow the DOM to register the removal of the class
my_square.className += ' fade';
},50);
}
document.getElementById('bt1').onclick = dim_fast_shine_slow;
Demo at http://jsfiddle.net/gaby/qFYL7/7/
It's as simple as:
function dim_fast_shine_slow() {
my_square.classList.toggle("dim_fast");
}
In your version you had:
function dim_fast_shine_slow() {
my_square.className = 'dim_fast'; //changes class to dim_fast
my_square.className = 'square'; // changes it back to square
}
In each click the element's class name will just end up being "square".
It's 2018 and this solution works in edge, chrome, opera and firefox. Does'nt work in my IE11 though caniuse says IE11 has full keyframes support.
const fade = document.querySelector('.fade');
const cont = document.querySelector('.container');
document.body.addEventListener('click', ev => {
if (ev.target.classList.contains('fade')) {
cont.classList.add('fade-out-in');
}
});
cont.addEventListener('animationend', ev => {
cont.classList.remove('fade-out-in');
});
#keyframes fadeOutIn {
0% { opacity: 0; }
100% { opacity: 1; }
}
.container {
width: 200px;
height: 200px;
margin-top: 10px;
background: red;
}
.fade-out-in {
animation: fadeOutIn 1s;
}
<button class="fade">Fade 1</button>
<button class="fade">Fade 2</button>
<button class="fade">Fade 3</button>
<div class="container"></div>
There should be a way of doing it without jQuery (which I am not aware of).. but in case u decide use jQuery :
$(my_square).hide("fast").show("slow");
Related
Greeting .
I already have the fade in animation.
When my dialog or box opens the animation is good.
However, the problem is that this does not happen when the animation is turned off at the click of the X button.
I want what happens now on fade in, happens on fade out too.
In short
when my dialog box pops up, animation pops up good
But I want to exit the dialog so that the animation is also scale down.
Code:
html
<div class="modal-dialog">
any content
// button which close animation
<button type="button" class="close" (click)="closeDialog()">
x
</button>
</div>
css
.modal.fade .modal-dialog {
animation-name: fade-in-scale-animation;
animation-duration: 0.3s;
}
#keyframes fade-in-scale-animation {
0% {transform: scale(0.5); opacity : 0 }
100% {transform: scale(1); opacity : 1}
}
EDIT:
Check this https://stackblitz.com/edit/angular-66n3nl
I want on close animation same as when a open?
You may apply a second class which has the animation, but dynamically.
const fadeInOutContainer = document.querySelector('#modal');
const fadeOut = () => {
fadeInOutContainer.classList.add('fade-out-container');
}
.fade-in-container {
background: black;
width: 200px;
height: 200px;
animation: fade-in 0.3s;
}
.fade-out-container {
animation: fade-out 0.3s;
}
#keyframes fade-in {
0% { opacity: 0; }
100% { opacity: 1; }
}
#keyframes fade-out {
0% { opacity: 1; }
100% { opacity: 0; }
}
<div class="fade-in-container" id="modal">
<!-- Content here... -->
</div>
<button onclick="fadeOut()">Fade out</button>
This is just a sample for the sake of example. The idea is there, adding a new class to the container itself.
I suppose the modal will not be displayed once the animation ends, that's why I leave this with the class on it. If this is not the case and the HTML element will be recycled for some reason, you should remove the dynamic class later.
Edit on demand
If you define an HTML Element with a class, the styles whitin that class will be applied by the time the element is just rendered.
*.html
<div class="test">Just for the sake of example</div>
*.css
.test { border: 1px solid red; }
Here, the container above will have a red border by the time the page loads (or the container displays).
Talking about animations, if we have
.test {
border: 1px solid red;
animation: anim 1s;
}
#keyframes anim {
0% { opacity: 0 }
100% { opacity: 1 }
}
The animation anim will be triggered at the same time the styles whitin the test class are being applied.
That is why you can't apply fade-in-container and fade-out-container to the container in your HTML file.
What you want is to trigger the fade-in animation first (whenever the container is rendered), and that is why the container is defined with that class. However, you want the fade-out animation to trigger whenever you want, with an event. Like you said, it must trigger whenever the button Xis clicked.
So, you need to listen the click event of that button, then trigger the fade-out animation.
When the fade-out animation will be triggered? Whenever you apply the fade-out-container class to the container.
So, to summerize,
in the *.html
<div class="fade-in-container id="modal">
<!-- Only the fade-in-container class -->
</div>
<button id="btn">Fade out</button>
and the script should look like something like
*.js
const container = document.querySelector('#modal');
const btn = document.querySelector('#btn');
btn.addEventListener(() => {
// By adding the class, the animation will be triggered
container.classList.add('fade-out-container');
});
Hope it clarifies a bit.
So I found this solution Using CSS for fade-in effect on page load And I've used Method 2 with raw JavaScript. Here's my code sample
JavaScript
var fadeOnLoad = function () {
document.getElementById("wrapper").className += "load";
};
fadeOnLoad();
CSS
#wrapper {
opacity: 0;
transition: opacity 2s ease-in;
}
.load {
opacity: 1;
}
Link to the website where it doesn't work https://skidle.github.io/projects/weather
And this text is crossed out in Google Dev tools
try to define
opacity: 1 !important;
id selector has higher priority than class
Here is a snippet with clear process logic. Element is invisible until body got loaded. As soon as event body onload fired, element gets opacity: 1;
function fadeOnLoad() {
document.getElementById("wrapper").className = "";
};
#wrapper {
transition: opacity 2s ease-in;
}
.not_loaded {
opacity: 0;
}
<body onload="fadeOnLoad()">
<div id="wrapper" class="not_loaded">text</div>
</body>
Add important to your class attribute.
.load{
opcacity: 1 !important; //because you have id selector with opacity to 0.
}
As a good practice, try to avoid using IDs for styling.
Instead of defining the transition in the #wrapper selector, create a class containing the transition property like so:
.opacity-transition {
transition: opacity 2s ease-in;
}
Once the transition ends, this class will not be needed any more and can be removed.
Create another class to initially hide the #wrapper element. When this class is removed it will trigger the transition.
.hidden {
opacity: 0;
}
Code Snippet:
function fadeOnLoad() {
//Cache the selector.
var wrapper = document.getElementById("wrapper");
console.log(wrapper.className);
//Add event listener for transition end.
wrapper.addEventListener("transitionend", function() {
//Remove the class which is not needed anymore.
this.classList.remove("opacity-transition");
console.log(this.className);
});
//Remove hidden class to start the transition.
wrapper.classList.remove("hidden");
};
.opacity-transition {
transition: opacity 2s ease-in;
}
.hidden {
opacity: 0;
}
<body onload="fadeOnLoad()">
<div id="wrapper" class="opacity-transition hidden">
text</div>
</body>
JSFIDDLE
I am trying to move a div in from off screen and then back on toggle
$('a.show').on('click',function() {
if($('#left-navi-designers').css('left')=='0px'){
$('#left-navi-designers').animate({left: '-100%'}, 1000);
}else{
$('#left-navi-designers').animate({left:0}, 1000);
}
});
That is what i have for the JavaScript. I have this for my CSS:
#left-navi-designers {
height: 100%;
position: fixed;
background: #fff;
width: 100%;
left: -100%;
}
This is my HTML:
<div id="left-icons"><a class="show" style="color:#999;">DUH!</a></div>
<div id="left-navi-designers">
<div id="topNavigation">
<ul class="topLevelNavigation">
<li>DESIGNERS</li>
<li>EMERGING</li>
<li>STUDIOS</li>
<li>NEW FACES</li>
<li>EDITORS</li>
<li>MEDIA KIT</li>
<li>BEAUTY</li>
<li>BRANDS</li>
<li>MODELS</li>
<li>PARTIES</li>
</ul></div>
I'm very new to this and am just trying to get some things figured out. Here is the site i am playing on http://keithfrenchdesigns.com/RunwayMag/designers_main.html
Thanks in advance!
you also can toggle your div with a css transition. This is more quick because you only have to toggle a class. See my example jsfiddle to see what I mean.
http://jsfiddle.net/8Wkgf/1/
jquery
$('button').on('click', function(){
$('#slider').toggleClass('open');
})
css
#slider{
background:blue;
height:100px;
width:500px;
position:relative;
left:-520px;
}
.open{
left:0px !important;
}
.transition{
-webkit-transition: left 0.3s ease-out; /* Chrome 1-25, Safari 3.2+ */
-moz-transition: left 0.3s ease-out; /* Firefox 4-15 */
-o-transition: left 0.3s ease-out; /* Opera 10.50–12.00 */
transition: left 0.3s ease-out; /* Chrome 26, Firefox 16+, IE 10+, Opera 12.10+ */
}
html
<button>slide</button>
<div id="slider" class="transition"></div>
Your code works and I see you have included jQuery UI, so instead using animate and negative left, you can use visibility and toggle with animation:
Display or hide the matched elements.
Code:
$('a.show').on('click', function () {
$('#left-navi-designers').toggle("slide", { direction: "left" }, 1000);
});
Demo: http://jsfiddle.net/IrvinDominin/r7m3C/
You can use this functions.
function SlideIn(el){
var elem = document.getElementById(el);
elem.style.transition = "left 1.5s linear 0s";
elem.style.left = "10px";
}
function SlideOut(el){
var elem = document.getElementById(el);
elem.style.transition = "left 1.5s linear 0s";
elem.style.left = "-200px";
}
// Use this buttons, for example.
<button onclick="SlideIn('box1')">Slide in</button>
<button onclick="SlideOut('box1')">Slide out</button>
<div id="box1">Put something in here</div>
This is just an example, try it at your own boxes.
I have tried your code like here http://jsfiddle.net/wm3c4/. And it works just fine the only problem I see is in your page you have this:
$('a.show').on('click',function() {
if($('#website').css('left')=='0px'){
$('#website').animate({left: '-100%'}, 1000);
}else{
$('#website').animate({left:0}, 1000);
}
});
But there is no element with id="website". Try to change that selector to the one you post here.
the code :
<div id="divtoBlink" ></div>
css:
#divtoBlink{
width:100px;
height:20px;
background-color:#627BAE;
}
javascript:
setInterval(function(){
$("#divtoBlink").css("background-color","red");
},100)
but nothing is happening can anyone tell me what i am doing wrong ?
fiddle Here
I suggest you don't change the color with javascript. It's better practice to do this via CSS. Changing styles should be done in a stylesheet, not in JS (in case if you want other/more properties changed).
You toggle a class, that class has a background definition (in this example, if you want you can add more properties). A fiddle as DEMO
<div id="divtoBlink" ></div>
.blinker{
background: red;
}
let $div2blink = $("#divtoBlink"); // Save reference for better performance
let backgroundInterval = setInterval(function(){
$div2blink.toggleClass("blinker");
},100)
If you feel like a wild mood, you can add some css3 animation to it
#div2blink{
transition: backgroundColor 0.05s ease-in-out;
}
Made a demo for the animation: DEMO (I slowed it down in the example!)
DEMO
setInterval(function () {
$("#divtoBlink").css("background-color", function () {
this.switch = !this.switch
return this.switch ? "red" : ""
});
}, 100)
.blink-div {
background: green;
animation: flash 2s ease infinite;
}
<div class="blink-div">
Hello World
</div>
Another way to animate a div is by using the css3 animations.
.blink-div {
animation: flash 2s ease infinite;
}
Yet another example, but with much color and speed (based on martijn's example). Seizure warning:
var $div2blink = $("#divtoBlink"); // Save reference, only look this item up once, then save
var color = 0
var color_classes = ["backgroundRed", "backgroundYellow", "backgroundBlue"];
var backgroundInterval = setInterval(function(){
color++;
if (color === 3){
color = 0;
}
$div2blink.toggleClass(color_classes[color]);
},10)
http://jsfiddle.net/LkuNB/1983/
You can also do it with pure CSS:
#divtoBlink{
-webkit-animation: bgblink 3s; /* Chrome, Safari, Opera */
-webkit-animation-iteration-count: infinite; /* Chrome, Safari, Opera */
}
#-webkit-keyframes bgblink {
from {background-color: #fff;}
50% {color:#000}
to {background-color: #fff;}
}
#keyframes bgblink {
from {background-color: #fff;}
50% {background-color:#000}
to {background-color: #fff;}
}
Please have a look at below code
HTML:
<div id="divtoBlink" ></div>
CSS:
#divtoBlink{
width:100px;
height:20px;
background-color:#627BAE;
}
.class2{
background-color:#ff0000 !important;
}
JS :
setInterval(function(){
$("#divtoBlink").toggleClass("class2");
},100)
Try this to change the color one time to "red", change background-color to backgroundColor
setInterval(function(){
$("#divtoBlink").css("backgroundColor","red");
},100)
If you want to toggle the class, than you have to do it with .toggle
I have a CSS3 animation that needs to be restarted on a click. It's a bar showing how much time is left. I'm using the scaleY(0) transform to create the effect.
Now I need to restart the animation by restoring the bar to scaleY(1) and let it go to scaleY(0) again.
My first attempt to set scaleY(1) failed because it takes the same 15 seconds to bring it back to full length. Even if I change the duration to 0.1 second, I would need to delay or chain the assignment of scaleY(0) to let the bar replenishment complete.
It feels too complicated for such a simple task.
I also found an interesting tip to restart the animation by removing the element from the document, and then re-inserting a clone of it:
http://css-tricks.com/restart-css-animation/
It works, but is there a better way to restart a CSS animation?
I'm using Prototype and Move.js, but I'm not restricted to them.
No need in timeout, use reflow to apply the change:
function reset_animation() {
var el = document.getElementById('animated');
el.style.animation = 'none';
el.offsetHeight; /* trigger reflow */
el.style.animation = null;
}
#animated {
position: absolute;
width: 50px; height: 50px;
background-color: black;
animation: bounce 3s ease-in-out infinite;
}
#keyframes bounce {
0% { left: 0; }
50% { left: calc( 100% - 50px ); }
100% { left: 0; }
}
<div id="animated"></div>
<button onclick="reset_animation()">Reset</button>
Just set the animation property via JavaScript to "none" and then set a timeout that changes the property to "", so it inherits from the CSS again.
Demo for Webkit here: http://jsfiddle.net/leaverou/xK6sa/
However, keep in mind that in real world usage, you should also include -moz- (at least).
#ZachB's answer about the Web Animation API seems like "right"™ way to do this, but unfortunately seems to require that you define your animations through JavaScript. However it caught my eye and I found something related that's useful:
Element.getAnimations() and Document.getAnimations()
The support for them is pretty good as of 2021.
In my case, I wanted to restart all the animations on the page at the same time, so all I had to do was this:
const replayAnimations = () => {
document.getAnimations().forEach((anim) => {
anim.cancel();
anim.play();
});
};
But in most cases people will probably want to select which animation they restart...
getAnimations returns a bunch of CSSAnimation and CSSTransition objects that look like this:
animationName: "fade"
currentTime: 1500
effect: KeyframeEffect
composite: "replace"
pseudoElement: null
target: path.line.yellow
finished: Promise {<fulfilled>: CSSAnimation}
playState: "finished"
ready: Promise {<fulfilled>: CSSAnimation}
replaceState: "active"
timeline: DocumentTimeline {currentTime: 135640.502}
# ...etc
So you could use the animationName and target properties to select just the animations you want (albeit a little circuitously).
EDIT
Here's a handy function that might be more compatible using just Document.getAnimations, with TypeScript thrown in for demonstration/fun:
// restart animations on a given dom element
const restartAnimations = (element: Element): void => {
for (const animation of document.getAnimations()) {
if (element.contains((animation.effect as KeyframeEffect).target)) {
animation.cancel();
animation.play();
}
}
};
Implement the animation as a CSS descriptor
Add the descriptor to an element to start the animation
Use a animationend event handler function to remove the descriptor when the animation completes so that it will be ready to be added again next time you want to restart the animation.
HTML
<div id="animatedText">
Animation happens here
</div>
<script>
function startanimation(element) {
element.classList.add("animateDescriptor");
element.addEventListener( "animationend", function() {
element.classList.remove("animateDescriptor");
} );
}
</script>
<button onclick="startanimation(
document.getElementById('animatedText') )">
Click to animate above text
</button>
CSS
#keyframes fadeinout {
from { color: #000000; }
25% {color: #0000FF; }
50% {color: #00FF00; }
75% {color: #FF0000; }
to { color : #000000; }
}
.animateDescriptor {
animation: fadeinout 1.0s;
}
Try it here: jsfiddle
If you have a class for CSS3 animation, for example .blink, then you can removeClass for some element and addClass for this element thought setTimeout with 1 millisecond by click.
$("#element").click(function(){
$(this).removeClass("blink");
setTimeout(function(){
$(this).addClass("blink);
},1 // it may be only 1 millisecond, but it's enough
});
You can also use display property, just set the display to none.
display:none;
and the change backs it to block (or any other property you want).
display:block;
using JavaScript.
and it will work amazingly.
The Animation API gives you full control over when and what to play, and is supported by all modern browsers (Safari 12.1+, Chrome 44+, Firefox 48+, Edge 79+) .
const effect = new KeyframeEffect(
el, // Element to animate
[ // Keyframes
{transform: "translateY(0%)"},
{transform: "translateY(100%)"}
],
{duration: 3000, direction: "alternate", easing: "linear"} // Keyframe settings
);
const animation = new Animation(effect, document.timeline);
animation.play();
Demo: https://jsfiddle.net/cstz9L8v/
References:
https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect/KeyframeEffect
https://developer.mozilla.org/en-US/docs/Web/API/Animation
There is an answer on MDN, which is similar to the reflow approach:
<div class="box">
</div>
<div class="runButton">Click me to run the animation</div>
#keyframes colorchange {
0% { background: yellow }
100% { background: blue }
}
.box {
width: 100px;
height: 100px;
border: 1px solid black;
}
.changing {
animation: colorchange 2s;
}
function play() {
document.querySelector(".box").className = "box";
window.requestAnimationFrame(function(time) {
window.requestAnimationFrame(function(time) {
document.querySelector(".box").className = "box changing";
});
});
}
If you create two identical sets of keyframes, you can "restart" the animation by swapping between them:
function restart_animation(element) {
element.classList.toggle('alt')
}
#keyframes spin1 {
to { transform: rotateY(360deg); }
}
#keyframes spin2 {
to { transform: rotateY(360deg); }
}
.spin {
animation-name: spin1;
animation-duration: 2s;
}
.alt {
animation-name: spin2;
}
div {
width: 100px;
background: #8CF;
padding: 5px;
}
<div id=_square class=spin>
<button onclick="restart_animation(_square)">
Click to restart animation
</button>
</div>
On this page you can read about restarting the element animation: Restart CSS Animation (CSS Tricks)
Here is my example:
<head>
<style>
#keyframes selectss
{
0%{opacity: 0.7;transform:scale(1);}
100%{transform:scale(2);opacity: 0;}
}
</style>
<script>
function animation()
{
var elm = document.getElementById('circle');
elm.style.animation='selectss 2s ease-out';
var newone = elm.cloneNode(true);
elm.parentNode.replaceChild(newone, elm);
}
</script>
</head>
<body>
<div id="circle" style="height: 280px;width: 280px;opacity: 0;background-color: aqua;border-radius: 500px;"></div>
<button onclick="animation()"></button>
</body>
But if you want to you can just remove the element animation and then return it:
function animation()
{
var elm = document.getElementById('circle');
elm.style.animation='';
setTimeout(function () {elm.style.animation='selectss 2s ease-out';},10)
}
setInterval(() => {
$('#XMLID_640_').css('animation', 'none')
setTimeout(() => {
$('#XMLID_640_').css('animation', '')
}, 3000)
}, 13000)
Create a second "keyframe#" which restarts you animation, only problem with this you cannot set any animation properties for the restarting animation (it just kinda pops back)
HTML
<div class="slide">
Some text..............
<div id="slide-anim"></div>
</div><br>
<button onclick="slider()"> Animation </button>
<button id="anim-restart"> Restart Animation </button>
<script>
var animElement = document.getElementById('slide-anim');
document.getElementById('anim-restart').addEventListener("mouseup", restart_slider);
function slider() {
animElement.style.animationName = "slider"; // other animation properties are specified in CSS
}
function restart_slider() {
animElement.style.animation = "slider-restart";
}
</script>
CSS
.slide {
position: relative;
border: 3px black inset;
padding: 3px;
width: auto;
overflow: hidden;
}
.slide div:first-child {
position: absolute;
width: 100%;
height: 100%;
background: url(wood.jpg) repeat-x;
left: 0%;
top: 0%;
animation-duration: 2s;
animation-delay: 250ms;
animation-fill-mode: forwards;
animation-timing-function: cubic-bezier(.33,.99,1,1);
}
#keyframes slider {
to {left: 100%;}
}
#keyframes slider-restart {
to {left: 0%;}
}
Note that with React, clearing the animation like this, a codesandbox I found helps.
Example I used in my code:
function MyComponent() {
const [shouldTransition, setShouldTransition] = useState(true);
useEffect(() => {
setTimeout(() => {
// in my code, I change a background image here, and call this hook restart then animation,
// which first clears the animationName
setShouldTransition(false);
}, timeout * 1000);
}, [curr]);
useEffect(() => {
// then restore the animation name after it was cleared
if (shouldTransition === false) {
setShouldTransition(true);
}
}, [shouldTransition]);
return (
<div
ref={ref2}
style={{
animationName: shouldTransition ? "zoomin" : "",
}}
/>
);
}
I found out a simple solution today. Using the example provided in this answer, you can just append the element again to the body:
function resetAnimation() {
let element = document.getElementById('animated');
document.body.append(element);
}
#animated {
position: absolute;
width: 50px;
height: 50px;
background-color: LightSalmon;
animation: bounce 3s ease-in-out infinite;
}
#keyframes bounce {
0% {left: 0;}
50% {left: calc(100% - 50px);}
100% {left: 0;}
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="animated"></div>
<button onclick="resetAnimation()">Reset</button>
</body>
</html>
Using Chrome's developer tools, the append does not actually append the element to the body and just replace it, probably because the same reference to the element is used.