How can I create the CSS animation below in JavaScript? I've looked all over Google, and tried multiple times to create this but I couldn't figure out how to do this.
#keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity: 100;
}
}
To run this, I know I can use what is shown below, but I don't know how to create this animation. Can anyone help?
element.style.animation = "fadeIn 5s linear";
You can use javascript with transition to achieve it
// start frame
const start = {
opacity: 0
};
// end frame
const end = {
opacity: 1
};
const element = document.querySelector('span');
Object.assign(element.style, start);
element.style.transition = 'all 5s linear';
requestAnimationFrame(() => {
Object.assign(element.style, end);
});
<span>Lorem Ipsum</span>
What do you mean exactly with "Create in Javascript"? Without using CSS?
If so, you can use a simple interval to update the opacity of the element until it reached 0 or 100. Simple example:
let opacity = 0;
const fadeEl = document.getElementById("fadeInElementIdWithOpacity0");
const fadeInInterval = setInterval(() => {
if (opacity < 1) {
opacity = opacity + 0.1
fadeEl.style.opacity = opacity;
} else {
clearInterval(fadeInInterval);
}
}, 200);
You can first define this function with whatever amount of intervals that you want and then call it with any querySelector
function fadeIn(x) {
var fade = document.querySelector(x);
var opacity = 0;
var intervalID = setInterval(function() {
if (opacity < 1) {
opacity = opacity + 0.1
fade.style.opacity = opacity;
} else {
clearInterval(intervalID);
}
}, 200);
}
havnig this function in console and running fadeIn(".-logo") will fade in the stackoverflow's logo
Related
When I'm linking Bootstrap 5 its just fading out the text instead of fading in.
When I remove the link everything just work fine.
const animatedText = document.querySelector(".fancy");
const strText = animatedText.textContent;
const splitText = strText.split("");
animatedText.textContent = "";
for (let i = 0; i < splitText.length; i++) {
animatedText.innerHTML += "<animated>" + splitText[i] + "</animated>";
}
let char = 0;
let timer = setInterval(onTick, 50);
function onTick() {
const animated = animatedText.querySelectorAll('animated')[char];
animated.classList.add('fade');
char++
if (char === splitText.length) {
complete();
return;
}
}
function complete() {
clearInterval(timer);
timer = null;
}
animated {
opacity: 0;
transition: all 0.4s ease;
}
animated.fade {
opacity: 1;
}
<h2 class="fancy">WELCOME TO MY WORLD</h2>
Bootstrap have .fade class in CSS which is responsible for "fade out" alert boxes.
Change your "fade" class to "text-fade" or something else and everything will be okay.
I am new to javascript and I have done one image to fade in, but the second image wont fade in next.
See HTML and Javascript. With the use of pure HTML, CSS AND JS without keyframes for animation. No libraries or framework to use.
For HTML:
<div id="female" style="opacity: 0;">
<img id="fem" src="./images/female.png" onload="female()">
</div>
<div id="headline1" style="opacity: 0;">
<img id="t1" src="./images/headline1.png" onload="headline1()">
</div>
</div>
For JS code:
//FEMALE ANIMATION
function female () {
var opacity = 0;
var intervalID = 0;
window.onload = fadeIn;
function fadeIn() {
setInterval(show, 150);
}
function show() {
var body = document.getElementById("female");
opacity = Number(window.getComputedStyle(body)
.getPropertyValue("opacity"));
if (opacity < 1) {
opacity = opacity + 0.1;
body.style.opacity = opacity
} else {
clearInterval(intervalID);
}
}}
//HEADLINE 1 ANIMATION
function headline1 () {
var opacity = 0;
var intervalID = 0;
window.onload = fadeIn;
function fadeIn() {
setInterval(show, 150);
}
function show() {
var body = document.getElementById("headline1");
opacity = Number(window.getComputedStyle(body)
.getPropertyValue("opacity"));
if (opacity < 1) {
opacity = opacity + 0.1;
body.style.opacity = opacity
} else {
clearInterval(intervalID);
}
}}
Both the functions female() and headline1() assign their own functions to window.onload. This will cause the 2 functions impact each other.
You can use window.addEventListener instead of window.onload to solve this issue.
Considering that both your female() and headline1() functions are very similar, it is a good idea to use a single function with a parameter to specify the ID of the image to animate.
function animateImage(id, opacity) {
var intervalID = 0;
window.addEventListener('load', fadeIn);
function fadeIn() {
setInterval(show, 150);
}
function show() {
var body = document.getElementById(id);
opacity = Number(window.getComputedStyle(body)
.getPropertyValue("opacity"));
if (opacity < 1) {
opacity = opacity + 0.1;
body.style.opacity = opacity
} else {
clearInterval(intervalID);
}
}
}
I was trying to make an animation using the style.transform property. The intention was to loop the transform scale property with slight increase in x and y on each round, but it failed. How can I achieve this effect?
x = document.getElementById("btn");
x.onclick = function() {
for (let y = 0; y < 1; y += 0.1) {
x.style.transform = 'scale(1.' + y + ',' + '1.' + y + ')';
}
}
<button id='btn'>button</button>
You should use CSS transitions.
Style your button like so:
#btn {
transition: transform 0.1s
}
That code will make the button transition during 0.1 seconds whenever the transform property is changed, for example the scale.
Then, from your JavaScript code, you juste have to assign the transform style once, and CSS will transition automatically.
x = document.getElementById("btn");
x.onclick = function() {
x.style.transform = 'scale(2,2)'; // or any x and y value
}
x = document.getElementById("btn");
x.onclick = function() {
x.style.transform = 'scale(2,2)'; // or any x and y value
}
#btn {
transition: transform 0.1s
}
<button id="btn">button</button>
You could do it with a combination of setInterval, requestAnimationFrame and CSS transitions to control the speed of the animation, good performance and a smooth controlled transition.
const button = document.getElementById("btn");
function scaleButton(speed, size = 1) {
let end = size * 2;
let interval = setInterval(() => {
if (size === end) {
clearInterval(interval);
button.style.transitionDuration = '';
}
size += 0.1;
size = parseFloat(size.toFixed(1)); // Round to 1 decimal point.
requestAnimationFrame(() => {
button.style.transform = `scale(${size}, ${size})`;
});
}, speed);
button.style.transitionDuration = `${speed}ms`;
}
button.onclick = function() {
scaleButton(50);
};
html {
width: 100%;
height: 100%;
}
body {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
}
#btn {
transition: transform linear;
}
<button id='btn'>button</button>
Here is a soultion using requestAnimationFrame;
x = document.getElementById("btn");
let y = 0;
function animate (y) {
if(y < 1) {
y += 0.1;
x.style.transform = `scale(${1 + y},${1 + y})`;
requestAnimationFrame( () => animate(y) );
}
}
x.onclick = function() {
animate(0);
}
<button id='btn'>button</button>
The browser has an, how to say, an painting cycle. Every 16ms (i am not sure if its exactly 16ms) the browser does an repaint.
The problem that you have, is that your loop is already done before the next repaint cycle.
Here is an solution with async / await:
You can create an function called readyToAnimate it returns an promise that resolves the callback function of the requestAnimationFrame.
The requestAnimationFrame callback gets executed before the next repaint.
Now in your loop you can use await readyToAnimate(). It will wait till the browser is ready for the next repaint.
x = document.getElementById("btn");
x.onclick = async function() {
for (let y = 0; y < 1; y += 0.1) {
await readyToAnimate();
x.style.transform = `translateX(${y * 200}px)`;
}
}
function readyToAnimate() {
return new Promise(res => requestAnimationFrame(res));
}
<button id='btn'>button</button>
I'm trying to optimize my code so that I can cycle through images on a splash page quickly and effectively. I've got it looking really smooth on chrome and safari but when I view the splash page on mobile and firefox it bugs out big time
A demo can be found at http://theotherchrisrock.com
I would love to hear your input on how to fix this. Here is the relevant code:
var i = 0
var j = 0
var l = $('.se-pre-con > div').length - 2;
var $pre_con = $('.se-pre-con');
var $di_sum = $('.splash-image:last-child');
var $img_array = [];
for (t = 0; t < l; t++) {
$img_array[t] = $('.splash-image-' + t);
}
function flashanimation() {
if (i < l) {
$img_array[i].addClass('flash');
i++;
flashloop();
} else if (j != 1) {
$di_sum.addClass('di-some');
j = 1
flashloop();
} else {
$pre_con.addClass('nun');
}
}
function flashloop() {
setTimeout(function() {
flashanimation();
}, 300)
}
$(".blinker").removeClass("blinker");
flashloop();
Basically, the goal is to make the image appear for 150ms and then disappear for 150ms and then next image appears and so on finally ending with just a black div. Right now I'm adding a class to each div which triggers this keyframe animation ~
.splash-image.flash {
-webkit-animation:flash 0.15s linear;
animation:flash 0.15s linear;
-webkit-animation-delay:0.15s;
animation-delay:0.15s;
display:block;
opacity:0;
}
#-webkit-keyframes flash {
0% {
opacity:0;
}
1% {
opacity: 1;
}
100% {
opacity:1;
}
}
#keyframes flash {
0% {
opacity:0;
}
1% {
opacity: 1;
}
100% {
opacity:1;
}
}
I would love to hear your input. Thank u for reviewing my question
I've made a simple box with CSS, I'm trying to fade it by dynamically changing it's opacity using the setInterval object.
http://jsfiddle.net/5gqRR/7/
CSS
#box {
margin:0px auto;
margin-top:10px;
height:50px;
width:50px;
background:black;
}
JAVASCRIPT
var fade;
function select(id) {
return document.getElementById(id);
}
function disBox() {
fade=setInterval(function(){
select("box").style.opacity-=0.1;
},300);
if (select("box").style.opacity==0) {
clearInterval("fade");
select("box").style.display="none";
}
else {
select("box").style.display="block";
}
}
The problem is that the "-=" operator starts subtracting the opacity from 0 instead of 1.
Can someone please explain why this happens?
Your check about the opacity should be inside the loop.
function select(id) {
return document.getElementById(id);
}
// Run at loading
window.onload = function () {
// Preload variables
var box = select('box'), opacity = 1, fade;
// Looping
fade = setInterval(function(){
// Calculate and applying opacity
opacity = Math.max( 0, opacity - 0.1 );
box.style.opacity = opacity;
// Stoping loop when box isn't visible
if ( !opacity )
clearInterval(fade);
},30);
};
​Demo: http://jsfiddle.net/5gqRR/8/
You can't set an onload event to div element. Instead of that you can do:
HTML
<div id="box"></div>
JavaScript
var fade;
function select(id) {
return document.getElementById(id);
}
function disBox() {
fade = setInterval(function(){
select("box").style.opacity-=0.1;
},300);
if (select("box").style.opacity==0) {
clearInterval("fade");
select("box").style.display="none";
}
else {
select("box").style.display="block";
}
}
window.onload = (function() {
disBox();
})();
Demo
According to edit
select("box").style.opacity = 1; // add this line to set initial opacity
fade = setInterval(function(){
select("box").style.opacity-=0.1;
},300);