How to change style with setTimeout in Javascript - javascript

(?) I want to change my class name 'box' from opacity '0' to opacity '1.0' like an animation or fade in every sec 1000ms, 2000ms. 3000ms,
(X) But I don't want to do something like this code but appears fade in like this Code on jsfiddle and not fade in at the same time like this Code on jsfiddle.
var DivB = document.getElementsByClassName("box");
setTimeout(function(){DivB[0].style.opacity = "1"}, 1000);
setTimeout(function(){DivB[1].style.opacity = "1"}, 2000);
setTimeout(function(){DivB[2].style.opacity = "1"}, 3000);
(/) I want to make It appears with the delays 1000,2000,3000 with javascript look shorter like using var 'i' to javascript like this .. Code on jsfiddle.
var DivB = document.getElementsByClassName("box");
var i;
function myFade(){
for (var i=0; i<DivB.length; i++){
setTimeout(function(){DivR[i].style.opacity="1"}, i*1000)}
}
myFade();

You're looking for setInterval
var DivB = document.getElementsByClassName("box");
var divIndex = 0;
var interval = setInterval(() => {
DivB[divIndex].style.opacity = "1";
divIndex++;
if (divIndex === divB.length - 1) clearInterval(interval);
} , 1000)
Basically, this will fire every one second, setting the opacity of divB[divIndex] to '1'. divIndex itself increments every interval as well. After all the DivB elements are processed, the interval will be cleared.

You can add transition: all 1s; to the box CSS from one of the code examples you posted:
var DivB = document.getElementsByClassName("box");
setTimeout(function(){DivB[0].style.opacity = "1"}, 1000);
setTimeout(function(){DivB[1].style.opacity = "1"}, 2000);
setTimeout(function(){DivB[2].style.opacity = "1"}, 3000);
.box { display:inline-block; position:relative; opacity:0;
transition: all 1s;}
<div class='box'>1</div><br/>
<div class='box'>2</div><br/>
<div class='box'>3</div><br/>

You can do this :
var DivB = document.getElementsByClassName("box");
function myFade() {
for (let i = 0; i < DivB.length; i++) {
setTimeout(() => {
DivB[i].style.opacity = "1"
}, i * 1000)
}
}
myFade();
.box {
display: inline-block;
position: relative;
opacity: 0;
}
<div class='box'>1</div>
<div class='box'>2</div>
<div class='box'>3</div>
I would suggest you to read the difference between var and let specially when using in loops with setTimeout and setInterval
Hope this helps !

Try it:
function fadeElementsProgressive(className, timePerElement = 1000) {
const divs = document.getElementsByClassName(className);
for(let i = 0; i < divs.length; i++) {
setTimeout(() => {
divs[i].style.opacity = 1;
}, i * timePerElement)
}
}
fadeElementsProgressive('box');
.box { display:inline-block; position:relative; opacity:0; }
<div class='box'>1</div><br/>
<div class='box'>2</div><br/>
<div class='box'>3</div><br/>
This will create a function that get a class name and execute a fade.

Related

Vanilla js fading out instead of fading in

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.

Looping through array of colors infinite amount of times

I have a button with a default background color(black). I want to change the background color (from an array) of this button when hovering over it. I have it working at a fundamental level, but I want it to repeat the loop over and over.
this is what i have so far.
var color = ['#3e50a2', '#faa51a', '#ed1c24', '#2a9446'];
var i = -1;
document.querySelector('.customBtn').addEventListener('mouseover', function() {
i = 1 < color.length ? ++i : 0;
document.querySelector('.customBtn').style.background = color[i]
});
document.querySelector('.customBtn').addEventListener('mouseout', function() {
document.querySelector('.customBtn').style.background = '#000';
})
<a class="customBtn">Button</a>
I think you tried to reset the value of i with this i = 1 < color.length ? ++i : 0; but it doesn't. This will continuously increase the value never resetting it because 1 is always less than the length of the array.
I think you meant to increment the value and then reset if it's too big:
i = ++i < color.length ? i : 0;
Here's the complete code. I've refactored the query selector as there's no point to doing it more than once, and changed the mouseout background colour so you can read the button
var color = ['#3e50a2', '#faa51a', '#ed1c24', '#2a9446'];
var i = -1,
btn = document.querySelector('.customBtn');
btn.addEventListener('mouseover', function() {
i = ++i < color.length ? i : 0;
btn.style.background = color[i];
});
btn.addEventListener('mouseout', function() {
// revert to default colour
btn.style.background = '';
})
<input type="button" class="customBtn" value="My button" />
Just replace i = 1 < color.length ? ++i : 0; with i = (i+1 < color.length) ? ++i : 0;. That's all.
var color = ['#3e50a2', '#faa51a', '#ed1c24', '#2a9446'];
var i = -1;
document.querySelector('.customBtn').addEventListener('mouseover', function() {
i = (i+1 < color.length) ? ++i : 0;
document.querySelector('.customBtn').style.background = color[i]
});
document.querySelector('.customBtn').addEventListener('mouseout', function() {
document.querySelector('.customBtn').style.background = '#000';
})
<a class="customBtn">Button</a>
If you must use javascript, take a look at the second example.
Pure CSS solution
You could accomplish this with a CSS animation, which would be both more efficient and less error prone. Unless there's a specific reason you need to use javascript here I'd strongly recommend this approach.
This example could be modified to do hard transitions instead of fading from one color to the next, but here's a quick demo:
button {
background: black;
color: white;
border: none;
padding: 0.5em 1em;
}
button:hover {
animation: buttonhover 1s infinite;
}
#keyframes buttonhover {
0% {
background: #3e50a2;
}
25% {
background: #faa51a;
}
50% {
background: #ed1c24;
}
75% {
background: #2a9446;
}
}
<button>Hello</button>
Javascript Solution
If you must use javascript for whatever reason, you can use the % operator to keep from running off the end of the colors array:
const colors = ['#3e50a2', '#faa51a', '#ed1c24', '#2a9446'];
let index = 0;
let interval;
const hover = (e) => {
interval = setInterval(() => {
e.target.style.backgroundColor = colors[index];
index = (index + 1) % colors.length;
}, 300);
}
document.querySelector('button').addEventListener('mouseover', hover);
document.querySelector('button').addEventListener('mouseout', (e) => {
clearInterval(interval);
e.target.style.backgroundColor = 'black';
});
button {
background: black;
color: white;
border: none;
padding: 0.5em 1em;
}
<button>Hello</button>

How to add animation to photos changing every 3 seconds?

The pictures change themselves every 3 seconds.
I would like to add simple animation to the photo during the change.
Preferably in vaniilla js.
let index = 1;
const changeImg = () => {
index++;
img.setAttribute('src', `img/img${index}.png`);
if (index === 3) {
index = 0;
}
};
setInterval(changeImg, 3000);
If you use something like animate.css, or create your own animation class you could do it like this:
(Im assuming you're getting the image by a query selector/getElementById)
let index = 1;
const changeImg = () => {
index++;
img.classList.add('animate__animated');
img.classList.add('animate__bounce');
setTimeout(() => {
img.setAttribute('src', `img/img${index}.png`);
img.classList.remove('animate__animated');
img.classList.remove('animate__bounce');
}, 300); // This delay is assuming the animation duration is 300ms, you need to change this to the length of the animation
if (index === 3) {
index = 0;
}
};
setInterval(changeImg, 3000);
As you suggested an example in vanilla JavaScript (no libraries), here you go.
(function slideShow() {
let imgs = [
"https://picsum.photos/id/237/200/300",
"https://picsum.photos/id/238/200/300",
"https://picsum.photos/id/239/200/300"
];
let index = 0;
const frontImg = document.getElementById("slideshow__img--front");
const backImg = document.getElementById("slideshow__img--back");
frontImg.src = imgs[index];
const changeSlideShowImg = () => {
const currImgSrc = imgs[index];
index++;
if (index >= imgs.length) index = 0;
const newImgSrc = imgs[index];
backImg.src = newImgSrc;
frontImg.classList.add("slideshow__img--fadeout");
setTimeout(() => {
frontImg.src = newImgSrc;
frontImg.classList.remove("slideshow__img--fadeout");
}, 500);
};
setInterval(changeSlideShowImg, 3000);
})()
.slideshow {
width: 200px;
height: 300px;
position: relative;
}
.slideshow__img {
position: absolute;
left: 0;
top: 0;
opacity: 1;
}
#slideshow__img--front {
z-index: 2;
}
.slideshow__img.slideshow__img--fadeout {
transition: opacity 0.5s ease-in;
opacity: 0;
}
<div class="slideshow">
<img id="slideshow__img--front" class="slideshow__img" />
<img id="slideshow__img--back" class="slideshow__img" />
</div>

Pause or Delay a loop on a array in a setInterval()

I want the color of the box I have created to change every 0.5 seconds, I have stored the colors in an array and I want the color to change every .5 seconds but it changes all at once.
<style type="text/css">
#box{
width: 100px;
height: 100px;
background: green;
}
</style>
</head>
<body>
<div id="box"></div>
<script type="text/javascript">
var colors = ['red','blue','green','violet','purple'];
var box = document.getElementById('box');
setInterval(function(){
for(var i=0; i < colors.length; i++){
box.style.backgroundColor=colors[i];
}
}, 300);
</script>
Depending on whether you want the box to continue changing after it has been through all the colours, there are a number of ways to solve this:
/*
Keeps running
*/
var colors = ['red','blue','green','violet','purple'],
i = 0;
setInterval(function () {
box.style.backgroundColor = colors[i++ % colors.length];
}, 500);
/*
Runs once only
*/
var colorsOnce = colors.slice(),
interval = setInterval(function () {
once.style.backgroundColor = colorsOnce.shift();
if(!colorsOnce.length) clearInterval(interval);
}, 500);
.box{
width: 100px;
height: 100px;
background: green;
}
<div id="box" class="box"></div>
<div id="once" class="box"></div>
Note: Despite these examples, where timing functions are involved best practice is generally to use a timeout as described by #AmmarCSE above.
You are looping inside the interval callback, which means that it will go through all the colors each interval.
Make the interval be the loop instead, i.e. go one step furter for each interval. Example:
var index = 0;
setInterval(function(){
box.style.backgroundColor = colors[index];
index = (index + 1) % colors.length;
},300);
Demo:
var colors = ['red','blue','green','violet','purple'];
var box = document.getElementById('box');
var index = 0;
setInterval(function(){
box.style.backgroundColor = colors[index];
index = (index + 1) % colors.length;
},300);
#box{
width: 100px;
height: 100px;
background: green;
}
<div id="box"></div>
Note: To actually get an interval that runs every 0.5 seconds, you should use 500 instead of 300 in the setInterval call.
Use setTimeout()
var colors = ['red', 'blue', 'green', 'violet', 'purple'];
var box = document.getElementById('box');
for (var i = 0; i < colors.length; i++) {
(function(index) {
setTimeout(function() {
console.log(index);
box.style.backgroundColor = colors[index];
}, 300 * i);
})(i)
}
#box {
width: 100px;
height: 100px;
background: green;
}
<div id="box"></div>
Two key points you missed in your code
Half a second is "500 milliseconds". So you need to change from 300 ms to 500ms in setInteval.
When the timer kicks in, you need to update the background color with the "next color in the array".
So you may try something like:
var color = 0;
var colors = ['red','blue','green','violet','purple'];
function nextColor(){
color ++;
if (color>=colors.length)
color = 0;
return colors[color];
}
setInterval(function(){
box.style.backgroundColor = nextColor();
},500);
This will keep the box changes its color every half a second and cycle through the color array endlessly.

Change div's hover state with jQuery timer

I’m a complete jquery newb and I want to create 5 classes(.button1 - .button5) with a timer which toggles the next classes :hover or :active state every 4000ms on a continuous loop. I also want the ability for the timer to halt and continue if another one of the classes is hovered on by the user. Does anyone know of a good starting point or a thread with a similar solution?
I’ve attached a diagram.
CSS
.wrapper { width:100%; margin:0 auto; background:#f3f3f3; }
#buttonblock { display:block; }
.button1, .button2, .button3, .button4, .button5 { display:inline-block; margin:0 5px; height:50px; width:50px; border-radius:25px; background:#3cc8dd; }
.button1:hover, .button2:hover, .button3:hover, .button4:hover, .button5:hover{ background:#fbc040; }
HTML
<div class="wrapper">
<div id="buttonblock">
<div class="button1"></div>
<div class="button2"></div>
<div class="button3"></div>
<div class="button4"></div>
<div class="button5"></div>
</div>
</div>
you can simply loop over the array of objects, for example
var $block = $('#buttonblock div');
for (var n=0; n<$block.length; n++)
{
var domELM = $block[n]; // you can do $(domELM) to create a jquery of the dom
// do stuff here, set interval or whatever it is you wish to do.
if(n == $block.elngth)
n=0; //resets the loop
}
HTML
<div class="wrapper">
<div id="buttonblock">
<div class="button button1"></div>
<div class="button button2"></div>
<div class="button button3"></div>
<div class="button button4"></div>
<div class="button button5"></div>
</div>
css
.hover {
background:#fbc040;
}
js
var counter = 1;
var timer;
$(document).ready(function () {
startTimer();
$('.button').mouseenter(function () {
$('.hover').removeClass('hover');
clearInterval(timer);
});
$('.button').mouseleave(function () {
startTimer();
});
});
function startTimer() {
timer = setInterval(function () {
counter = (counter > 5) ? 1 : counter;
$('.hover').removeClass('hover');
$('.button' + counter).addClass('hover');
counter++;
}, 4000);
}
JSFiddle
Try this
var divs = $('#buttonblock').children('div'),
number = divs.length,
currentIndex = 0,
intervalLength = 2000;
function setTimer() {
divs.removeClass('hover');
divs.eq(currentIndex).addClass('hover');
currentIndex++;
if (currentIndex == number) {
currentIndex = 0;
}
}
setTimer();
var timer = setInterval(setTimer, intervalLength);
divs.mouseenter(function () {
clearInterval(timer);
divs.removeClass('hover');
var div = $(this);
div.addClass('hover');
currentIndex = divs.index(div);
}).mouseleave(function () {
timer = setInterval(setTimer, intervalLength);
});
Example - setInterval
or using setTimeout

Categories

Resources