JS animation Loop Transitions - javascript

var i = 1;
const title = document.getElementById("display-heading");
var texts = [
"Karibu",
"Bienvenido",
"স্বাগতম।",
"Willkommen",
"أهلا بك",
"Bienvenue"
];
title.textContent = texts[0];
var loop = setInterval(function() {
title.textContent = texts[i];
i = (i+1) % texts.length; // Allows the array to loop
}, 1000);
How would I add a fade in/slow down the transition?
https://codepen.io/elliebrayton/pen/vYJBOBP

There is a little discrepancy between the CSS and the HTML: the HTML has an id attribute with name "display-heading", while the CSS defines attributes for a class with that name.
You can get the fading going by changing the opacity.
Here is a runnable snippet:
const title = document.getElementById("display-heading");
var texts = [
"Karibu",
"Bienvenido",
"স্বাগতম।",
"Willkommen",
"أهلا بك",
"Bienvenue"
];
title.addEventListener("transitionend", loop);
function loop() {
if (title.style.opacity != "1") {
texts.push(title.textContent = texts.shift());
title.style.opacity = 1;
} else {
setTimeout(() => title.style.opacity = 0, 500);
}
}
setTimeout(loop);
#display-heading{
font-size: 30px;
transition: 0.5s opacity;
opacity: 0;
}
<h1 id='display-heading'>Welcome</h1>

Related

How do I add fade in fade out to inner HTML?

How can I get the fade in and fade out when the array item changes in inner HTML ? I would like it to fade out and disappear and then the next language to fade in to appear.
var langs = ["Tamil", "Hindi", "Kannada", "Malayalam"];
var count = 0;
var langLength = langs.length;
var language = document.querySelector(".language");
setInterval(e => {
count = count % langs.length;
var newColour = langs[count];
language.innerHTML = `${newColour}`
count = count + 1;
}, 1500);
.language {
font-weight: bold;
}
<div class="content">
This language <span class="language"></span> <br>
is an Indian language.
</div>
You can use an infinite animation in CSS. Set the duration of the animation equal to the value used for setinterval.
var langs = ["Tamil", "Hindi", "Kannada", "Malayalam"];
var count = 0;
var langLength = langs.length;
var language = document.querySelector(".language");
setInterval(e => {
count = count % langs.length;
var newColour = langs[count];
language.innerHTML = `${newColour}`
count = count + 1;
}, 1500);
.language {
font-weight: bold;
animation: fadeOutIn 1.5s infinite;
}
#keyframes fadeOutIn {
0%,
100% {
opacity: 0
}
50% {
opacity: 1
}
}
<div class="content">
This language <span class="language"></span> <br> is an Indian language.
</div>

Animation: Fade in when creating an element and fade out when deleting

I'm having trouble with the following situation.
I have a button which acts like a normal toggle. When I click on the "Animate" button, I want the <p>This is new Div</p> to fade in when I again click on the Animate button, this <p> should fade out.
How can I achieve this?
const main = document.getElementById('main');
const btn = document.getElementById('btn');
let show = false;
btn.addEventListener('click', () => {
if(show) {
const newDiv = document.getElementById("new-div");
newDiv.remove();
show = false;
} else {
const newDiv = document.createElement('div');
newDiv.id = "new-div";
newDiv.innerHTML = "<p>This is new Div</p>";
main.appendChild(newDiv);
show = true;
}
})
#new-div {
transition: all 2s ease-in-out;
}
<div id="main">
<button id="btn">Animate</button>
</div>
I'm actually building a gallary layout app, which requires to fade in when clicked on a image + show in full screen, then fade out to its original position when clicked. Since there will be many images, I want to use JS to dynamically work on this.
And the biggest hurdle so far is to implement fade-out, because the element is being deleted.
Based on your information I've made a refined version, pls see fiddle and code below: https://jsfiddle.net/Kenvdb/8nsbp16o/
JavaScript:
const main = document.getElementById('main');
const btn = document.getElementById('btn');
let toggledDiv = null;
btn.addEventListener('click', () => {
if (!toggledDiv) {
show();
} else {
hide();
}
})
const show = () => {
toggledDiv = document.createElement('div');
toggledDiv.id = "content";
toggledDiv.style.opacity = "1";
toggledDiv.innerHTML = "<p>This is new Div</p>";
main.appendChild(toggledDiv);
}
const hide = () => {
toggledDiv.style.animation = "fade-out 0.5s ease-in";
toggledDiv.style.opacity = "0";
toggledDiv.addEventListener('animationend', remove);
toggledDiv.addEventListener('webkitAnimationEnd', remove);
}
const remove = () => {
toggledDiv.remove();
toggledDiv = null;
};
CSS:
#content {
opacity: 0;
animation: fade-in 0.5s ease-in;
}
#keyframes fade-in {
0% { opacity: 0; }
100% { opacity: 1; }
}
#keyframes fade-out {
0% { opacity: 1; }
100% { opacity: 0; }
}
HTML:
<div id="main">
<button id="btn">Animate</button>
</div>
You'll need to set the opacity to 0 first. Then you can apply a keyframe animation.
Otherwise, the element has nothing to transition from.
See below.
#new-div {
opacity: 1;
animation: fadeIn 2s ease-in-out;
}
#keyframes fadeIn {
from {
opacity: 0;
}
}
There's several ways of doing this. You can set the opacity of the newly added element using the style attribute:
const main = document.getElementById('main');
const btn = document.getElementById('btn');
let show = false;
let fading = false;
btn.addEventListener('click', () => {
if (fading) return;
if (show) {
const newDiv = document.getElementById("new-div");
newDiv.style = "opacity: 0"; // start the fade
fading = true;
window.setTimeout(function() {
fading = false; // disable showing/hiding while fading
newDiv.remove(); // remove after fade completed
show = false;
}, 2000);
} else {
show = true;
const newDiv = document.createElement('div');
newDiv.id = "new-div";
newDiv.innerHTML = "<p>This is new Div</p>";
main.appendChild(newDiv);
window.setTimeout(function() {
newDiv.style = "opacity: 1"; // Start fading after a minimal time
});
}
})
#new-div {
transition: all 2s ease-in-out;
opacity: 0;
}
<div id="main">
<button id="btn">Animate</button>
</div>
Or you can use jQuery, which significantly reduce the code:
$("#btn").on('click', () => {
var newDiv = $("#new-div");
if (newDiv.length) {
newDiv.stop().fadeOut(2000, function() {
newDiv.remove();
});
} else {
$(`<div id='new-div'>
<p>This is new Div</p>
</div`).appendTo("#main").hide().fadeIn(2000);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main">
<button id="btn">Animate</button>
</div>
You can do it simply using both of fadeIn() and fadeOut() methods in jQuery.
Here is an example:
let alreadyClicked = false;
$("#btn").click(function() {
if(alreadyClicked == false) {
$("p").remove(); //Remove the paragraph if already created.
$("#main").append("<p style='display: none;'>Hello, world!</p>"); //Create a paragraph.
$("p").fadeIn(); //Show it by fading it in.
alreadyClicked = true;
} else {
$("p").fadeOut(); //Fade it out
alreadyClicked = false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main">
<button id="btn">Animate</button>
</div>

Set transition between innerHTML

Need to add fade in and out transition on innerHTML.
I have looked around but didn't find a solution to accomplish this.
I wish to have fade in and out effect between innerHTML texts.
var h2text = ["First h2", "Second H2"];
var counter = 0;
var h2 = document.getElementById("changeH2");
var inst = setInterval(change, 2000);
function change() {
h2.innerHTML = h2text[counter];
counter++;
if (counter >= h2text.length) {
counter = 0;
}
}
<h2 id="changeH2"></h2>
You can utilise CSS classes and transitions to do this by fading the element in and out when the text changes. I've also included another timeout.
var h2text = ["First h2", "Second H2"];
var counter = 0;
var h2 = document.getElementById("changeH2");
var inst = setInterval(change, 2000);
function change() {
h2.classList.add('fade');
setTimeout(function(){
h2.innerHTML = h2text[counter];
h2.classList.remove('fade');
counter++;
if (counter >= h2text.length) {
counter = 0;
}
}, 500);
}
h2{
transition: opacity .5s ease;
}
.fade{
opacity: 0;
}
<h2 id="changeH2"></h2>
Improved a little your js (using modulo instead of your three-line-condition), and created a small animation that seems to fit your requirements.
let h2text = ["First h2", "Second H2"];
let counter = 0;
let h2 = document.getElementById("changeH2");
let inst = setInterval(change, 2000);
function change() {
h2.innerHTML = h2text[counter];
counter = (counter + 1) % h2text.length;
}
#changeH2{
opacity: 0;
animation: fade infinite 2s;
}
#keyframes fade{
20%{
opacity: 1;
}
80%{
opacity: 1;
}
}
<h2 id="changeH2"></h2>
You could achieve this bij using the opacity like this
var h2text = ["First h2", "Second H2"];
var h2 = document.getElementById("changeH2");
h2.style.transition = "0.5s"; //fade speed
setTimeout(function () {
h2.style.opacity = 0; //make text temporarily invisible
setTimeout(function() {
h2.innerHTML = h2text[1];
h2.style.opacity = 1; //fade back in
}, 500); //this timeout needs to be the same as the transition speed
})
<h2 id="changeH2">First h2<h2/>
Here you don't have to do anything with your css.
Simple plugin for text transition.
(function($) {
let KeyWord = ["First h2", "Second H2"];
let counter = 0;
let Flag = true;
function rotaterator() {
setTimeout(function() {
if (counter == 2) {
counter = 0;
}
if (Flag) {
Flag = false;
counter = 1;
}
$("#changeH2").fadeOut(function() {
$("#changeH2").text(KeyWord[counter]);
counter++;
}).fadeIn(function() {});
rotaterator();
}, 2000);
}
rotaterator();
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2 id="changeH2"></h2>

Button text transition with pure Javascript

I have a fade in function made with pure javascript as this site shows.
function fadeIn(el) {
var opacity = 0;
el.style.opacity = 0;
el.style.filter = '';
var last = +new Date();
var tick = function() {
opacity += (new Date() - last) / 400;
el.style.opacity = opacity;
el.style.filter = 'alpha(opacity=' + (100 * opacity)|0 + ')';
last = +new Date();
if (opacity < 1) {
(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
}
};
tick();
}
What I need is to apply this transition in a change of button text, something like:
var firstChild = document.getElementById('my-button').firstChild;
firstChild.data = 'Another text';
fadeIn(firstChild);
Of course this do not works as expected, but I wanted something to achieve a behavior that on a change text, a fade in transition is triggered only to the text, not to the entire button.
Is there a way to achieve this?
Since you're using firstChild i assume your text is inside a child element of the button element, if that is the case, this will work.
Click the blue "run code snippet" button at the bottom to see it in action.
btn.addEventListener('click', function(){fadeOut(this.firstChild, newText)});
var newText = "World!";
function fadeOut(e, nT) {
o=1;
t=setInterval(function () {
if(o <= 0.1){
clearInterval(t);
e.style.filter = "alpha(opacity=0)";
if(nT != undefined) {
e.innerHTML = nT;
fadeIn(e);
}
}
e.style.opacity = o;
e.style.filter = 'alpha(opacity='+o*100+")";
o-=o*0.05;
}, 10);
}
function fadeIn(e) {
o=0;
t=setInterval(function () {
if(o >= 0.9){
clearInterval(t);
e.style.filter = "alpha(opacity=1)";
}
e.style.opacity = o;
e.style.filter = 'alpha(opacity='+o*100+")";
o+=0.05;
}, 25);
}
#btn {
color: Black;
width: 100px;
border: 1px solid black;
}
<button id="btn"><p>hello</p></button>
To change the text colour, using this function, you can set it's colour using RGBA - the A stands for the alpha channel.
So, something like this:
el.style.color = "rgba(0,0,0, "+ OPACITY +")" // Opacity is 0 - 1
You could also make your code more modular, allowing you to edit any style property with this fade function.
function fadeIn(el,prop,color) {
var opacity = 0;
el.style[prop] = 0;
var last = +new Date();
var tick = function() {
opacity += (new Date() - last) / 400;
el.style[prop] = "rgba("+color+","+opacity+")";
last = +new Date();
if (opacity < 1) {
(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
}
};
tick();
}
now you could do both:
fadeIn(firstChild,"background", "255,0,0"); // fade in background to red
fadeIn(firstChild,"color", "0,0,0"); // fade in text to black

Why isn't it possible to change max-height with % in javascript?

I'm trying to build a responsive menu, with a hamburger icon. I want the menu list to slide in and out, no jquery - pure javascript only.
HTML :
<div id="animation">
</div>
<button id="toggle">Toggle</button>
CSS :
div {
width: 300px;
height: 300px;
background-color: blue;
}
Javascript :
var but = document.getElementById('toggle');
var div = document.getElementById('animation');
var animate = function(type, callback){
var inter = -1, start = 100, end = 0;
if(type==true){
inter = 1;
start = 0;
end = 100;
}
var si = setInterval(function(){
console.log('maxheight');
div.style.maxHeight = (start + inter) + '%';
if(start == end){
clearInterval(si);
}
}, 10);
}
var hidden = false;
but.onclick = function(){
animate(hidden, function(){
hidden = (hidden == false) ? true : false;
});
}
div.style.maxHeight = "50%";
The problem is that proportional height in an element needs a fixed height on the parent, and you didn't provided any parent with a fixed height because for the maxHeight property too the % Defines the maximum height in % of the parent element.
You have to put your div in a parent container with a fixed height, this is your working code:
var but = document.getElementById('toggle');
var div = document.getElementById('animation');
var animate = function(type, callback) {
var inter = -1,
start = 100,
end = 0;
if (type) {
inter = 1;
start = 0;
end = 100;
}
var si = setInterval(function() {
console.log('maxheight');
div.style.maxHeight = (start + inter) + '%';
if (start == end) {
clearInterval(si);
}
}, 10);
}
var hidden = false;
but.onclick = function() {
animate(hidden, function() {
hidden = !hidden ;
});
}
div.style.maxHeight = "50%";
#animation {
width: 300px;
height: 300px;
background-color: blue;
}
#parent {
width: 500px;
height: 500px;
}
<div id="parent">
<div id="animation">
</div>
<button id="toggle">Toggle</button>
</div>
Note:
As stated in comments there are some statements in your JavaScript code that need to be adjusted:
if(type==true) can be written as if(type).
hidden = (hidden == false) ? true : false; can be shortened to hidden = !hidden
There seems to be a few errors with your code. I have fixed the js and added comments to what I have changed
var but = document.getElementById('toggle');
var div = document.getElementById('animation');
var animate = function (type, callback) {
var start = 100,
end = 0;
if (type) {
start = 0;
end = 100;
}
var si = setInterval(function () {
if (type) { // check whether to open or close animation
start++;
} else {
start--
}
div.style.maxHeight = start + '%';
if (start == end) {
clearInterval(si);
}
}, 10);
callback.call(this); // do the callback function
}
var hidden = false;
but.onclick = function () {
animate(hidden, function () {
hidden = !hidden; // set hidden to opposite
});
}
/*make sure parent container has a height set or max height won't work*/
html, body {
height:100%;
margin:0;
padding:0;
}
div {
width: 300px;
height: 300px;
background-color: blue;
}
<div id="animation"></div>
<button id="toggle">Toggle</button>
Example Fiddle

Categories