Triggering CSS3 Keyframes with javascript multiple times - javascript

I am triggering CSS3 Keyframes with javascript but its working for with first call after that any call to that function doesn't animate my div.
Here the Javascript code
function animateShare (imgSrc){
var share = document.getElementById("shareTools");
share.style.animation = "testAnimate 1s ease-in-out 0s"
//shareTools.style.animationPlayState = "running";
}
Sample of the issue (Click red box to preview)
var box = document.getElementById("box");
function animateBox(){
box.style.animation = "box 1s ease-in-out 0s";
}
#box{
background:red;
width:100px;
height:100px;
}
#keyframes box {
50%{width:300px;}
}
<div id='box' onclick='animateBox()'><div>
JSFIDDLE
I want it to animate everytime i call this function.

You can use well known hack: destroy and create element to reset animation.
var box = document.getElementById("box");
function animateBox(){
//destroy and create hack
document.body.removeChild(box);
document.body.appendChild(box);
box.style.animation = "box 1s ease-in-out 0s";
}
#box{
background:red;
width:100px;
height:100px;
}
#keyframes box {
50%{width:300px;}
}
<div id='box' onclick='animateBox()'><div>

In case someone is still interested by this there is another trick that works:
Changing the dataset value to something it has never been, and then use a css matching on that data.
I used this technique when animating the collapsing/uncollapsing of a menu, which of course can happen multiple times. Here's how I did it:
#menu[data-closed^="1"]{
animation:menu_closing;
}
#menu[data-closed^="0"]{
animation:menu_opening;
}
So the animation is based on the first character of the dataset (1 or 0).
Then in the click event that wants to close/open the menu:
var closed = menu_ele.dataset.closed // closed right now
? parseInt( menu_ele.dataset.closed.substr(0,1) )
: 0; // assuming menu is initialized open
var counter = menu_ele.dataset.closed // nb of times the menu was closed or open
? parseInt( menu_ele.dataset.closed.substr(1) )
: 0;
menu_ele.dataset.closed = ''+(1-closed)+(counter+1);
This way the "closed" dataset variable changes like this at every click:
11 (closing for the first time)
02 (reopening for the first time)
13
04
15
06
...
The first digit indicates whether it is currently closed, while all the rest is a counter to make the value new every time.

Think about your code - after first call it does nothing, becouse it already changed animation property of that element.
According to this CSS-Tricks article:
function animateShare (imgSrc){
var share = document.getElementById("shareTools");
share.style.animation = "testAnimate 1s ease-in-out 0s";
shareTools.style.animationPlayState = "paused";
shareTools.style.animationPlayState = "running";
}

add this code in the body section after the element for which the animation is being played-
<script>
document.getElementById('shareTools').addEventListener("animationend", function () {
this.removeAttribute("style");
})
</script>
or if you dont want to remove style attribute ,because you have other css than animation then create a class and add class dynimacally and remove it as above code.

You can reset the animation by just removing the animation property from the styles of the element after the animation has complete - removing the element is unnecessary. In my example, I set the duration in JS, but you could just as easily add an animationend hook to keep it simpler.
JSFiddle
var duration = 1000;
document.getElementById('box').addEventListener('click', function onClick(ev) {
var el = this;
el.style.animation = 'box ' + (duration / 1000 + 's') + ' ease-in-out';
setTimeout(function() {
el.style.animation = ''
}, duration);
});
#box {
background: red;
width: 100px;
height: 100px;
}
#keyframes box {
50% {
width: 300px;
}
}
<div id='box'><div>

Related

Is it possible to add a transition (like in CSS) in Javascript?

I have a Javascript code that shows a tooltip when hovering over an HTML element. Now I want to give this element a latency of about 6 milliseconds. In CSS it is very easy with the transition command. However, I did not find a transition style command in Javascript. Is there a solution or do I have to change to another programming language?
Javascript code:
var bghtooltipin = document.getElementById('bgh-tooltipin1');
var bghtooltipout = document.getElementById('bgh-tooltipout1');
bghtooltipin.addEventListener('mouseover', bghtooltipinmouseOver);
bghtooltipin.addEventListener('mouseout', bghtooltipoutmouseOut);
function bghtooltipinmouseOver() {
bghtooltipout.innerHTML = 'Go to Login';
bghtooltipout.style.color = "white";
bghtooltipout.style.top = "0";
}
function bghtooltipoutmouseOut() {
bghtooltipout.innerHTML = ' ';
bghtooltipout.style.top = "-99999px"
}
You can use something like this:
bghtooltipout.style.transition = "all 6s";
something like this it works is Vanila JS
bghtooltipout.style.transition = "all 2s";
There are 2 ways to interpret "latency". I will show you how to perform both implementations.
Delay.
6ms would pass, and then the transition would play. In JavaScript, this is done as the following:
setTimeout(function() {
// Code here
}, delay_in_ms);
Duration.
If you want your animation to last for 6ms, then you would do something as follows:
const element = document.querySelector("#testthing");
element.addEventListener("mouseover", function(){
this.style.opacity = "0";
this.style.transition = "opacity 0.6s";
});
element.addEventListener("mouseout", function(){
this.style.opacity = "1";
this.style.transition = "opacity 0.6s";
});
#testthing {
width: 100px;
height: 100px;
background: red;
}
<div id="testthing"></div>
PLEASE NOTE: In this example, the transition actually lasts for 600 milliseconds, not 6. This is because 6ms is just too quick to see. It just appears as an instant change.

Make a Header disappear and reappear after waiting 2 seconds

I ANSWERED DOWN BELOW
I want to make the header of my document once scrolled play an animation to fade and then use style.display to make it unusable. Here is the code:
<script type="text/javascript">
function Scroll()
{
var head = document.getElementById('header')
if (window.pageYOffset > 1)
{
head.style.display = "none";
head.style.opacity = "0";
} else {
head.style.display = "block";
head.style.opacity = "1";
}
}
window.addEventListener("scroll",Scroll);
</script>
I don't know how to make this though so that it will wait two seconds before running the document.getElementById('header').style.display = "none".
I have in the <style> tag to do the fade out animation with the .opacity, it is just the .display that I want to make wait the 2 seconds of animation.
Also I have no idea how to use JQuery or other documents' code so I need it to be purely in HTML, JavaScript or CSS. Thanks. (I'm a noob)
If what you need is to run after 2 seconds
For that you can make use of setInterval or setTimeout depending on your needs.
setTimeout(function(){ alert("This is after 3 sec"); }, 3000);
setInterval : Runs after every specified time interval.
setTimeout : Runs only once after waiting specified time.
W3CSchool Doc
If what you need is to wait till the DOM is loaded.
For that you will have to check the event DOMContentLoaded.
whatever the code you have it should be within this.
document.addEventListener("DOMContentLoaded", function (event) {
function Scroll()
{
var head = document.getElementById('header')
if (window.pageYOffset > 1)
{
head.style.display = "none";
head.style.opacity = "0";
} else {
head.style.display = "block";
head.style.opacity = "1";
}
}
window.addEventListener("scroll",Scroll);
}
I hope this solved your problem.
The best way to approach this for performance and maintainability is to let css handle the animation and only use javascript to capture the event and add a class.
Also, you need a way to make sure the function bound to the scroll event only fires once.
Finally, if you want to destroy the element, you can use javascript to listen for the 'animationend' event (the name is browser-dependent), which is captured by the browser, and fire your function to destroy the element at that time (instead of having a fixed 2 second delay as you are trying to do).
Here's a codepen demo of the implementation I just described: http://codepen.io/anon/pen/NdWGqO
Here's the relevant js and css:
//js
var head = document.getElementById('header');
var hasScrolled = false;
function onScroll() { // a function should only start with a capital letter if it is a constructor
if (!hasScrolled) {
head.className += " fade-out";
window.removeEventListener("scroll",onScroll); // remove this so it only fires once
}
hasScrolled = true; // this prevents the class from being added multiple times
}
function destroyElement() {
head.className += " hidden"; // the 'hidden' class will give the element 'display : none'
}
function captureEvents () {
window.addEventListener("scroll",onScroll);
// capture the animation end event, there are better ways to do this to support all browsers FYI
head.addEventListener("animationend", destroyElement);
head.addEventListener("webkitAnimationEnd", destroyElement);
head.addEventListener("oanimationend", destroyElement);
head.addEventListener("MSAnimationEnd", destroyElement);
}
document.addEventListener("DOMContentLoaded", captureEvents);
//css
.hidden {
display: none;
}
.fade-out {
animation-name: fadeOut;
animation-duration: 4s;
animation-iteration-count: 1;
animation-fill-mode: forwards;
-webkit-animation-name: fadeOut;
-webkit-animation-duration: 4s;
-webkit-animation-iteration-count: 1;
-webkit-animation-fill-mode: forwards;
}
#keyframes fadeOut {
from {opacity: 1; }
to {opacity: 0; }
}
#-webkit-keyframes fadeOut {
from {opacity: 1; }
to {opacity: 0; }
}
I figured it out... here is the code for js:
<script type="text/javascript">
function Scroll()
{
var head = document.getElementById('header');
var timeOut;
var displayNone = 'head.style.display = "none"'
if (window.pageYOffset < 1)
{
clearTimeout(timeOut);
}
if (window.pageYOffset > 1)
{
timeOut = setTimeout(function(){displayNone}, 2000);
head.style.opacity = "0";
} else {
head.style.display = "block";
head.style.opacity = "1";
stopcount();
}
}
window.addEventListener("scroll",Scroll);
Then in css:
#header
{
height: 100px;
width: 100%;
position: fixed;
background:radial-gradient(circle,#777,#666);
transition:all 0.2s;
}
And finally in HTML:
<header id="header"></header> /* header info goes in here */
idk why but when I set the display none part to a variable it fixed it.

Fading in and out with ES6 and CSS3

So I have a function that I'm trying to create the loops through an array to update a div's innerHTML with JavaScript. I was hoping to set the opacity to 0 and then 1 between setting the new data each time, without using jQuery's fadeIn() and fadeOut().
Here is what I have so far. I think I'm very close, but not sure what I'm doing that's slightly off.
Thanks!
slide(index, tweets, element) {
let self = this;
element.innerHTML = data[index].text;
element.style.opacity = 1;
setTimeout(() => {
index++;
element.style.opacity = 0;
setTimeout(self.slide(index, data, element), 2000);
}, 5000);
}
EDIT
I forgot to mention I'm banking on CSS3 for animation by adding a class to my div that changes with this:
transition: opacity 2s ease-in-out;
I don't know how the code you provided relates to the problem at hand, but here's a simple demo on how to fade out, change the text and then fade back in.
You should be able to expand on this for your needs.
var d = document.querySelector("div");
window.addEventListener("load", function() {
d.classList.add("hidden");
});
var i = 0;
d.addEventListener("transitionend", function() {
if (this.classList.contains("hidden")) {
i++;
this.innerHTML = "SUCCESS! ---> " + i;
}
this.classList.toggle("hidden");
});
div {
opacity: 1;
transition: opacity 2s;
}
div.hidden {
opacity: 0;
}
<div>LOADING...</div>
It just adds the hidden class to trigger the fade out and it binds a transitionend handler to change the text and remove the class for the fade in.

Div Transition With Javascript

I'm new to html and javascript. Some days back someone provided me with javascript which basically opens a hidden DIV and when other DIV is opened, the first DIV which was opened will close automatically. But now I'm having another problem which does not allow me to have a transition effect. I want a transition within this code. Please help!!!
Here is the JAVASCRIPT:
var divs = ["div1", "div2", "div3", "div4", "div5", "div6", "div7", "div8"];
var visibleDivId = null;
function toggleVisibility(divId) {
if (visibleDivId === divId) {
visibleDivId = null;
} else {
visibleDivId = divId;
}
hideNonVisibleDivs();
}
function hideNonVisibleDivs() {
var i, divId, div;
for (i = 0; i < divs.length; i++) {
divId = divs[i];
div = document.getElementById(divId);
if (visibleDivId === divId) {
div.style.display = "block";
} else {
div.style.display = "none";
}
}
}
And the HTML goes something like this:
<div id="div1" onClick="toggleVisibility('div1');return false;">
<div id="div2" onClick="toggleVisibility('div2');return false;">
and so on.
I have tried every possible way I could find, but there is no perfect way of achieving the effect. I want the div to be hidden and when the navigation is clicked, the div should open with its contents inside with a transition. Thank you :)
Try using CSS transitions. For example, this will give your divs a transition from collapsed to open over two seconds:
#div1 {
transition: height 2s;
-moz-transition: height 2s; /* Firefox 4 */
-webkit-transition: height 2s; /* Safari and Chrome */
-o-transition: height 2s; /* Opera */
}
I don't know JavaScript, but you will use it to hide the div by default, then on hover or click or whichever action you decide, have it display/hide the divs relative to their respective statuses.
As TylerH noted in the comments, the best way is to use CSS transition:
#mydiv { transition: opacity 2s; }
.hidden { opacity: 0; }
the role of the javascript could be just toggle the class .hidden on the element you want to hide:
document.getElementById("mydiv").classList.toggle("hidden");
See working example on the fiddle
You can't achieve it by setting the display property, since there is no transition between none and block. You can iterate through all the divs like you do in your hideNonVisibleDivs() and put it together with the fiddle code.
you can use Jquery animate
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script> <--- this will add Jquery
$("div").onclick(function(){
$(this.attr("id")).fadeIn(1000); <--- this is the animation
});
or if you want you can use the animate function
https://api.jquery.com/animate/

How do I select an element inside of a div using Jquery

My Jquery isn't working with the way I'm selecting the <p> and <img> elements. How could I get it to work?
function projectanim(x)
{
var Para = x.getElementsByTagName("p");
var Imgs = x.getElementsByTagName("img");
if ($(x).height() != 200)
{
$(x).animate({height:'200px'});
$(Para[0]).animate({display:'inline'});
$(Imgs[0]).animate({display:'inline'});
}
else
{
$(x).animate({height:'25px'});
$(Para[0]).animate({display:'none'});
$(Imgs[0]).animate({display:'none'});
}
}
Without the HTML this is just a shot in the dark but I assume you're trying to get the paragraph and image in a specific div?
Try this:
var Para = x.find("p");
var Imgs = x.find("img");
Although depending on what you're actually passing as x will determine whether it will actually work...
function projectanim (projectId) {
$('p, img', $('div#' + projectId)) // Select p/img tags children of <div id="projectId">
.slideDown(); // show using slideDown, fadeIn() or show('slow')
}
// Example
projectanim ('protflolio_project');
The idea with jQuery is:
Use the right selectors
With the right methods
Examples
Different ways to select all img and p tags under a div which id is my_div:
// The easy way
p_and_img = $('#my_div p, #my_div img');
// Using the context parameter
p_and_img = $('p, img', $('#my_div'));
// Using the context parameter and making sure my_div is a div
p_and_img = $('p, img', $('div#my_div'));
// only the first p and img
p_and_img = $('p:eq(0), img:eq(0)', $('#my_div'));
Your question is really, really vague, but from what I can gather, this is what you're looking at achieving:
function projectanim(x) {
var self = $(x);
if (self.height() === 200) {
self.animate({ height : '25px' })
.find('p,img').fadeOut()
;
} else {
self.animate({ height : '200px' })
.find('p,img').fadeIn()
;
}
}
That being said though, barring browser compatibility and all that shizz, you really should be doing something like this using CSS more than Javascript.
Depending on your parent element (say, a <div>), you can write up CSS like the following:
div {
height : 200px;
transition : height .5s linear;
}
div.active {
height : 25px;
}
div img,
div p {
display : inline;
opacity : 100;
transition : opacity .5s linear;
}
div.active img,
div.active p {
opacity : 0;
}
and just toggle a class on/off with your Javascript:
function projectanim(x) {
$(x).toggleClass('active');
}
and everything should be automatic. Your Javascript becomes waaaaaay simpler, less coupled, more maintainable, and your styles are right where they should be (in CSS files).
"what i'm trying to do is fade the and to inline from none."
Do you just want and to fade in? Or do you want it to go from display:none to inline and fade in?
I'll show you how to do both, and you can take away parts if you just want the fade in feature.
First off set p, and img as display:none; and opacity:0, in the css like so
p, img
{
display:none;
opacity:0;
}
Secondly your js has to alter the display of both , and tags and fade in/out like so.
function projectanim(x)
{
if ($(x).height() != 200)
{
$(x).animate({height:'200px'});
document.getElementsByTagName("p").style.display = 'inline';
document.getElementsByTagName("img").style.display = 'inline';
$("p").animate({"opacity": "1"}, 1000);
$("img").animate({"opacity": "1"}, 1000);
}
else
{
$(x).animate({height:'25px'});
$("p").animate({"opacity": "0"}, 500);
$("img").animate({"opacity": "0"}, 500);
document.getElementsByTagName("p").style.display = 'none';
document.getElementsByTagName("img").style.display = 'none';
}
}

Categories