How to Do Fade-In and Fade-Out With JavaScript and Css

How to do fade-in and fade-out with JavaScript and CSS

Ok, I've worked it out

element.style.opacity = parseFloat(element.style.opacity) + 0.1;

Should be used instead of

element.style.opacity += 0.1;

Same with

element.style.opacity = parseFloat(element.style.opacity) - 0.1;

Instead of

element.style.opacity -= 0.1;

Because opacity value is stored as string, not as float. I'm still not sure though why the addition has worked.

Fade In and Fade Out using pure Javascript in a simple way

I wrote this due to the title of the question: "Fade in ... pure javascript ... simple way."

tl;dr https://jsfiddle.net/nqfud4j0/

The following solution is a basic example of how you can use only Javascript to fade in/out to a desired value. You could also use this with other values/properties, but it also serves as an example for basic tweening.

It's intentionally using setInterval rather than requestAnimationFrame to demonstrate the example's use of time + controlled framerate rather than a delta or 'fast as possible.' A good solution would abstract this logic into a tweening library that combines both RAF + intervals to manage latency between frames.

function fadeTo(element, toValue = 0, duration = 200) {
// Store our element's current opacity (or default to 1 if null)
const fromValue = parseFloat(element.style.opacity) || 1;

// Mark the start time (in ms). We use this to calculate a ratio
// over time that applied to our supplied duration argument
const startTime = Date.now();

// Determines time (ms) between each frame. Sometimes you may not
// want a full 60 fps for performance reasons or aesthetic
const framerate = 1000 / 60; // 60fps

// Store reference to interval (number) so we can clear it later
let interval = setInterval(() => {
const currentTime = Date.now();

// This creates a normalized number between now vs when we
// started and how far into our desired duration it goes
const timeDiff = (currentTime - startTime) / duration;

// Interpolate our values using the ratio from above
const value = fromValue - (fromValue - toValue) * timeDiff;

// If our ratio is >= 1, then we're done.. so stop processing
if (timeDiff >= 1) {
clearInterval(interval);
interval = 0;
}

// Apply visual. Style attributes are strings.
element.style.opacity = value.toString();
}, framerate)
}


// Element reference
const element = document.querySelector('div');

// Fade in and out on click
element.addEventListener('click', e => {
// Animates our element from current opacity (1.0) to 0.25 for 1000ms
fadeTo(element, 0.25, 1000);

// Waits 1s, then animates our element's opacity to 1.0 for 500ms
setTimeout(() => {
fadeTo(element, 1.0, 500);
}, 1000);
});

How to make a created div in Javascript fade in and fade out?

I'm not sure if you forgot to copy a portion of your CSS but you don't seem to have any actual animations. If you want those effects you can use the CSS that https://animate.style/ provides either by importing it or extracting it from their GitHub files if you just want the two animations. But if you're going to use the animation attribute, you need some kind of keyframe animation built out otherwise nothing is going to happen. The forwards value lets the animations play and then doesn't repeat them so it's not flashing after the user clicks the button.

Also, you had some broken JS but that was a simple mistake.

Worth reading: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Animations/Using_CSS_animations so you can see how all of the attributes can be animated and controlled

function myFunction() {
var test = document.querySelector('#color');
var x = document.createElement('div');
if(test.style.color == ""){
test.style.color = "red";
x.innerHTML ='Liked this tournament!';
x.id = "snackbar";
x.className = "show";

} else{
test.style.color = "";
x.innerHTML='Removed like from this tournament!'
x.id = "snackbar";
x.className = "show";

}
document.body.appendChild(x);

}
#snackbar {
visibility: hidden;
min-width: 250px;
margin-left: -125px;
background-color: #333;
color: #fff;
text-align: center;
border-radius: 2px;
padding: 16px;
position: fixed;
z-index: 1;
left: 10%;
bottom: 30px;
font-size: 17px;
}

#snackbar.show {
visibility: visible;
animation: fadeIn 0.5s, fadeOut 0.5s 2.5s forwards;
}

@keyframes fadeIn {
from {
opacity: 0;
}

to {
opacity: 1;
}
}

@keyframes fadeOut {
from {
opacity: 1;
}

to {
opacity: 0;
}
}

.fadeOut {
animation-name: fadeOut;
}

.fadeIn {
animation-name: fadeIn;
}
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
<ul>
<li onclick="myFunction();"><a href="#/">click me<i id="color" class="fas fa-heart"></i></a></li>
<li><a href="#">not me<i class="fas fa-plus"></i></a></li>
<li><a href="#">or me<i class="fas fa-expand"></i></a></li>
</ul>

I can make an div fade in onclick, but how do i make it fade out?

Easier approach using jQuery animation, no CSS animation

function scrollToAccept() {
const terms = document.querySelector('.terms-and-conditions');
const button = document.querySelector('.accept');
// const watch = document.querySelector('.watch');

if (!terms) {
return; // quit function because there is no terms
}

// fires on page load because can't find element
function obCallback(payload) {
// console.log(payload[0].isIntersecting); // whether element is in view or not
// console.log(payload[0].intersectionRatio); // how much of the element is showing
if (payload[0].intersectionRatio === 1) {
button.disabled = false;
// stop observing the last element
ob.unobserve(terms.lastElementChild);
}
}

// takes in callback parameter
// will be called every time it needs to check if something is currently on the page
// watcher (needs to be told what to watch
const ob = new IntersectionObserver(obCallback, {
root: terms,
threshold: 1,
});

// call observe method on what we want to watch
// ob.observe(watch);
ob.observe(terms.lastElementChild);

}
scrollToAccept();

$('.yes').on('click', function(e) {
e.preventDefault();
$('.TOSHIDE').fadeToggle(3000).toggleClass('active');
//$(this).parents('ul').next().toggleClass('active');
});
body {
background: #ffffff;
}

.wrapper-all {
min-height: 94vh;
display: grid;
justify-content: center;
align-content: center;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
line-height: 2;
}

.wrapper {
width: 400px;
height: 80vh;
padding: 20px;
border: 1px solid black;
background: white;
display: grid;
grid-template-rows: 1fr auto;
}

button {
background: #133C55;
color: white;
font-size: 1rem;
padding: 20px;
transition: opacity 0.2s;
}

button[disabled] {
opacity: 0.1;
/* transform: translateX(-300%) scale(0.5); */
}

.terms-and-conditions {
overflow: scroll;
}

footer {
background-color: #192718;
width: 100%;
padding: 8px 0;
margin-top: 8px;
}

footer .container {
width: 800px;
margin: 0 auto;
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
justify-content: space-between;
align-items: flex-start;
}

footer .container a {
color: #fff;
}

footer a:hover {
color: #fce26a;
}

.tacbox {
display: block;
padding: 1em;
margin: 2em;
border: 3px solid #ddd;
background-color: #eee;
max-width: 800px;
}

input {
height: 2em;
width: 2em;
vertical-align: middle;
}

.TOSHIDE {
display: none;
}

.TOSHIDE.active {
display: block;
opacity: 1;
}
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Terms of Service</title>
<link rel="stylesheet" href="./scroll-to-accept.css" />
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>

<body>

<script>
function unhideTOS() {
document.getElementById("text").style.display = "";
}
</script>

<script>
function unlockBTN() {
document.getElementById("text").style.display = "";
}
</script>

<div class="tacbox">
<!-- The code for the checkbox + download if checked. -->
I agree to these ‌<a href="#tos" class="yes">Terms and Conditions.</a>
<br>
<a id="text" style="display:none" href="file.doc" Download>Download!</a>
</div>

<div class="TOSHIDE">
<div class="wrapper-all">
<div class="wrapper">
<div class="terms-and-conditions">
<h1>Terms and Conditions</h1>
<p>Disclaimer THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. You are the Current Maintainer of the Software, and to permit recipients of the Licensed Product for any such warranty, support,
indemnity or liability obligations to one or more recipients of Covered Code. However, You may do so in a commercial product offering.</p>
<hr>
</div>
<button class="accept" disabled autocomplete="off" id="myCheck" onclick="unlockBTN()">Accept</button>
</div>
</div>
</div>
<script src="./scroll-to-accept.js"></script>
</body>

</html>

How to make an image fade in and another fade out with one button click?

A few mistakes, and a few things to improve.

Inside your if conditionals, you were assigning the value of 1 and 2 to the variable currentscene instead of using the comparison operator ==. I added the remainder operator to be able to continue the loop indefinitely.

Instead of grabbing the element from the dom each loop, I just defined the elements at the top, and continued to reference the save variable.

instead of using a css keyframes animation, I used the css transition property to add animation to the changing of opacity.

If you have any questions, please ask /p>

let currentscene = 0;
const blue = document.getElementById("blue");;
const red = document.getElementById("red");;

function next() {
currentscene++;
if (currentscene % 2 == 0) {
blue.classList.remove("opaque");
red.classList.add("opaque");
}
else if (currentscene % 2 == 1) {
red.classList.remove("opaque");
blue.classList.add("opaque");
}
}
.squareblue,
.squarered {
height: 50px;
width: 50px;
position: absolute;
opacity: 0;
animation-fill-mode: forwards;
transition: 1s;
}

.squareblue {
top: 50px;
background-color: blue;
}

.squarered {
top: 100px;
background-color: red;
}

.opaque {
opacity: 1;
}

button {user-select: none}
<div2 id="blue" class="squareblue"></div2>
<div2 id="red" class="squarered"></div2>

<button class="button" onclick="next()">next</button>

Fade in and Fade out using JavaScript and HTML

I have editted your code and i works how you want.

var delta = .002;var fadeOut_opacity = 1;var fadeIn_opacity = 0;
function fading() {
disappear();}
function disappear() { document.getElementById("div21").style.opacity = fadeOut_opacity; document.getElementById("div22").style.opacity = fadeIn_opacity;
fadeOut_opacity -= delta; fadeIn_opacity += delta;
if (fadeIn_opacity >= 1) return;
timer = setTimeout("disappear()", 1);}
.special1 {  opacity: 0.0;  position: absolute;  height: 175px;  margin-right: 25px}
.visible1 { opacity: 1.0; position: absolute; height: 175px; margin-right: 25px;}
<body onLoad="fading()">
<div id="div21" class="visible1"> <img src="https://via.placeholder.com/150?text=image%201" alt="img1" /> </div> <div id="div22" class="special1"> <img src="https://via.placeholder.com/150?text=image%202" alt="img2" /> </div>
</body>


Related Topics



Leave a reply



Submit