Does an element animation run after setting display to a visible state? - javascript

Does an animation run after setting the display to block?
I'm setting the animation style of an element and then setting the display from none to block. It is playing the animation for me but I've read that display doesn't trigger animations. Who is correct?
Part of the Code:
// method 1 - enable a media query
var animation = "fadein 1s ease-out";
element.style.setProperty("animation", null, "important");
element.style.setProperty("animation", animation, "important");
enableQuery(rule); // manually enable a media query
// method 2 - set display none to block
element.style.display = "block";
var animation = "fadein 1s ease-out";
element.style.setProperty("animation", null, "important");
element.style.setProperty("animation", animation, "important");
CSS
#keyframes fadein {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
If you display is none outside of a media query and then you enable a media query that sets the display to block then that would cause the animation to play? Does requestAnimationFrame fit into any of this?

From the specification:
Setting the display property to none will terminate any running animation applied to the element and its descendants. If an element has a display of none, updating display to a value other than none will start all animations applied to the element by the animation-name property, as well as all animations applied to descendants with display other than none.
I have nothing more to add. I guess it's pretty clear.

Related

Removing class from element isn't triggering css animation

I'm building a carousel (slideshow) effect for my website and I have little issue. At every image change I want to make fade effect. So I've added a class with animation for it. And here the problem comes.
This function is firing every 3 sec (setInterval)
let sliderInterval = setInterval(nextImg, 3000);
function nextImg() {
imgChange(sliderNum + 1);
}
const heroImg = document.querySelector('.hero__image');
function imgChange(x) {
heroImg.classList.remove("fade");
sliderNum = (x + imgLocations.length) % imgLocations.length;
heroImg.src = imgLocations[sliderNum];
heroImg.classList.add("fade");
}
Fade effect:
.fade {
animation: fade 1.5s ease-in-out;
}
#keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
<div class="hero">
<img class="hero__image" src="photo1">
</div>
It works only for first image switch. Altough at the start of function it shall remove the class fade I see in function that it stays there in element and won't gone. It doesn't matter if I try to put this effect on hero section or img within it.
The problem is that css animations with keyframes will by default only run once. It is possible to alter the amount of times they run, but that will run them constantly in a loop which is undesirable.
Instead, what needs to happen is the animation needs to be reset. In order to do this, the element needs to have its animation name removed (fade in this case). This can be done with animation-name: none;, however, the rule needs to be placed on the element when fade is removed. Note the change to the selector to make the fade animation name take precedence when applied.
On top of this, it is important to note that if you remove and add the same class in a function, due to the way that browsers work, nothing will happen. In order for the browser to recognize any changes made, a page repaint must occur (here is a list of what makes that happen). In order to force the page to repaint, I chose to use offsetHeight, which is why you see heroImg.offsetHeight used in the code (note that it only needs to be read, it doesn't have to be used or assigned).
I mocked your image with a div for convenience.
let sliderInterval = setInterval(imgChange, 3000);
const heroImg = document.querySelector('.imgMock');
function imgChange() {
heroImg.classList.remove("fade");
heroImg.offsetHeight; // force repaint to recognize `animation-name: none;`
heroImg.classList.add("fade");
}
.imgMock.fade {
animation: fade 1.5s ease-in;
}
#keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
.imgMock {
height:50px;
width:50px;
background-color:black;
animation-name: none;
}
<div class="hero">
<div class="imgMock"></div>
</div>

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

How to instantly update a smoothly updating progress bar?

Bit of a specific question but I have a progress bar traveling from 100% to 0% over 10 seconds and I would like to, upon clicking a button, to jump it to whatever percent and continue from there. Here is a fiddle so far:
https://jsfiddle.net/41o6xvyt/
This kinda works except for the fact I have to use a timeout and some instant css switching trickery to get it to work (and even then it may not work on slower computers and it loses however many milliseconds). I was wondering if there was a better way that didn't require timeouts or this kind of hack in order to work.
The reason why you need the setTimeout() it is because the changes are cached by the browser and only applied after the entire script executes. The setTimeout allows one script to execute, then another after the timeout. This allows the CSS changes to be applied. In your example if we only call b() here is what's going on:
$("#first").css({ 'transition-duration' : '0s' }); // Cache change1
$("#first").css("width","50%"); // Cache change2
$("#first").css({ 'transition-duration' : '5s' }); // Overwrite change1
$("#first").css("width", "0%"); // Overwrite change2
// Apply style changes
The first changes to transition-duration and width practically never even existed, and never where applied since it was all done at the end of the script.
If you read the offsetHeight property of the element it will flush the cache and apply the changes, this will force the changes made to the CSS to be applied.
Also you will need to do is change the progress bars width to be set in CSS rather than as an attribute (as the flush only affects the CSS and not the items directly in style).
$("#report_jump").click(function(){
$("#first").css({ 'transition-duration' : '0s' });
$("#first").css("width","50%");
$("#first")[0].offsetHeight; // flush CSS, the above changes will now be applied
b();
});
Fiddle Example
Note
The "instant css switching trickery" isn't really trickery. We simply want to change the width to 50% and do so in 0 seconds. That's why the 'transition-duration' : '0s' is necessary.
you could try using keyframe
http://jsfiddle.net/j44gbwna/3/
#keyframes loader {
0% {left: 0px;}
99% { left: 100%;}
}
#-webkit-keyframes loader {
0% {width: 0%;left:0;right:0}
50% { width: 100%;left:0;right:0}
99% { width: 0%;left:100%;right:0}
}
I edited your codes and found a solution
$("#report_start").click(function(){
$("#first").removeClass('notransition');
$("#first").css("width","0%");
});
$("#report_jump").click(function(){
$("#first").css("width","50%");
$("#first").addClass('notransition'); // to remove transition
var dummyDelay=$("#first").width();
$("#report_start").trigger('click');
});
And add class in css
.notransition {
-webkit-transition: none !important;
-moz-transition: none !important;
-o-transition: none !important;
-ms-transition: none !important;
transition: none !important;
}
See live
https://jsfiddle.net/mailmerohit5/jbL3n4kj/

Assigning classes to a slide within a basic css slider

Basically I have a really simple (makes a change) slider that is done with css only. There are labels for the nav buttons and they are unique for each slide. Question is , How can I add/remove classes to certain items within the slide ONLY WHEN the slide is navigated to.
As with sliders they tend to load everything when the slider loads and I want to add cool animations to the bits on the slides so makes it pointless if everything loads at slide one.
jsfiddle http://jsfiddle.net/greggy_coding/013481b9/3/
I have provided some jsfiddle mock up of the slider and the classes animated and fade which are the ones in this instance i want to add and remove on the specific slide loading .. I will then assign them to different bits on the slide...
.animated {
-webkit-animation-duration: 1s;
animation-duration: 1s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
}
.fadeInUpBig {
-webkit-animation-name: fadeInUpBig;
animation-name: fadeInUpBig;
opacity: 0.3;
background-color: rgba(0,0,0,0.3);
}
CSS allows you to create animations with transitions and keyframes that once were only possible with JavaScript or Flash. Unfortunately, with CSS there’s no way to perform a callback when an animation is complete. With JavaScript, it’s possible to detect the end of a CSS transition or animation and then trigger a function.
Using JavaScript, we can detect the transitionend event; however for cross-browser, support we need to include the other browsers’ prefixes.
$(function() {
//Store a ref to slides
var $slides = $(".slides");
//Bind event to the contianed that gets animated
$(".slide-container")
.on("transitionend webkitTransitionEnd oTransitionEnd msTransitionEnd", function(e){
// Remove classes from all the elements within the active container that starts with the class 'add-anim'
$slides.find(".slide-container [class^='add-anim']").removeClass("animated bounceInLeft bounceInUp");
//Add appropriate classes to the matched elements within the active container
var $radio = $slides.find(":radio[name='radio-btn']:checked");
$radio.next(".slide-container").find(".add-anim-up").addClass("animated bounceInUp");
$radio.next(".slide-container").find(".add-anim-left").addClass("animated bounceInLeft");
});
});
Here is your entire code with HTML+JS+CSS.
Note: The above solution works, but the problem is, depending on the browser, it can fire twice (i.e. Chrome supports both webkitTransitionEnd and transitionend). There are ways to overcome this though, by detecting the supported event property. Take a look at this demo for more details.
Hope that helps.

Why does the transition not work?

I got a Section named "login" and a Section named "register".
When the opacity of them changes, I want to have a linear transition that take 0.3 seconds.
CSS:
#login{
opacity: 0;
transition:opacity 0.3s linear;}
#register{
opacity: 0;
display: none;
transition:opacity 0.3s linear;}
When you go on the Homepage HERE and click on "Query",
the opacity of #login changes to 1. That works fine with the transition!
When you click "oder registriere dich neu" below the Login-Form,
the Login-Section gets opacity: 0 again - then get display: none.
That also works perfect with a transition.
BUT than the REGISTER-Section is put to display: block and then opacity: 1 (after a setTimeout of 500 Milli-seconds.)
This don't have a transition! why?
When i click "Hast du schon einen Account?" again (to get back to the login),
the register Block will fade out with a transition perfecty again, and the login-form comes up without a transition again?
Here's the Javascript code for setting the opacities:
function changeSection(IDOut, IDIn)
{
var IDOut = "#" + IDOut;
var IDIn = "#" + IDIn;
hideSection(IDOut);
showSection(IDIn);
}
function hideSection(IDOut)
{
$(IDOut).css({opacity: "0"});
setTimeout(function(){
$(IDOut).css({display: "none"});
},500);
}
function showSection(IDIn)
{
setTimeout(function(){
$(IDIn).css({display: "block"});
$(IDIn).css({opacity: "1"});
},500);
}
IDOut is the Section, I want to Fade out (witch works perfect for login and register).
IDIn is the Section, I want to Fade in (witch DON'T WOKR for login and register)!
Why does the transition not work for IDIn?
Any Ideas?
You are using jQuery, you can do this alot simpler and let the jQuery handle it for you.
instead of your code for showSection and hideSection, use:
$('#yourselector').fadeIn(300);
to fade an element in with a time of 300 miliseconds, and:
$('#yourselector').fadeOut(300);
to hide it.
The transition does not work according to your code.
The IDIn originally has the display property as none and opacity as 0.
According to the function showSection, you first wait for 500ms, and then set the display and opacity property simultaneously to what you want. Concurrency is the problem, because display and opacity are changed in one animation frame at the same time, but the browser has to choose one property to transit. And it choose display.
More technically, transition only works on elements that are visible and have dimension. The width and height must not be zero. So display:none; cancels out your transition.
So the solution is easy, just put display outside of your setTimeout. Make display changed first.
The benefit over native jQuery method fadeIn is that it utilizes css transition, which is more efficient than jQuery's underlying animation.
function showSection(IDIn)
{
$(IDIn).css({display: "block"});
setTimeout(function(){
$(IDIn).css({opacity: "1"});
},500);
}

Categories