setTimeout not working as intended with css - javascript

var myIndex = 0;
var lastIndex = null;
var slides;
window.onload = function ()
{
slides = document.getElementsByClassName("mySlides");
slidePictures();
}
function slidePictures() {
slides[myIndex].style.display = "block";
slides[myIndex].className += " fadeIn";
console.log(slides[myIndex]);
setTimeout(function ()
{
slides[myIndex].className = "mySlides";
console.log(slides[myIndex]);
setTimeout(function ()
{
slides[myIndex].style.display = "none";
console.log("display none");
}, 1000);
}, 2000);
lastIndex = myIndex;
myIndex++;
if (myIndex >= 3)
return;
setTimeout(slidePictures, 4000);
}
.slidesDiv>img {
width: 80%;
height: 80%;
margin-left: 10%;
opacity: 0;
transition: opacity 1s;
}
.fadeIn {
opacity: 1 !important;
transition: opacity 1s;
}
<div class="slidesDiv">
<img class="mySlides" src="//placehold.it/200x80/0fb">
<img class="mySlides" src="//placehold.it/200x80/0bf">
<img class="mySlides" src="//placehold.it/200x80/fb0">
<img class="mySlides" src="//placehold.it/200x80/0fb">
<h1 id="indicator"> Indicator </h1>
</div>
So my issue is that, the image fades in the first time, but then doesn't fade out afterwards, nor does it disappear?
It's definitely problem with the setTimeout functions and I'm wondering what I'm doing/assuming incorrectly.

I edited your code a bit for cleanliness and I also removed the extra transition from .fadeIn as you already had it part of slidesDiv>img.
In your example your program flow is a bit hard to understand, and you are using a lot of variables which are not clear where they come from (like slides and myIndex) so that was part of the reason why it was difficult to figure why it was failing.
Hopefully I understood correctly what you were trying to achieve and the below should work for you. It's definitely not the best in terms of readability and you might be able to extract some of the nested setTimeouts into other functions, but I didn't want to modify too much of your initial code:
var myIndex = 0;
var lastIndex = null;
var slides;
window.onload = function() {
slides = document.querySelectorAll(".mySlides");
slidePictures(slides);
}
function slidePictures(slides) {
var time = 0;
slides.forEach((slide) => {
setTimeout(() => {
slide.style.display = "block";
slide.className += " fadeIn";
setTimeout(function() {
slide.className = "mySlides";
setTimeout(function() {
slide.style.display = "none";
}, 1000);
}, 2000);
}, time);
time += 4000;
});
}
.slidesDiv>img {
width: 80%;
height: 80%;
margin-left: 10%;
opacity: 0;
transition: opacity 1s;
}
.fadeIn {
opacity: 1 !important;
}
Please see this Pen for complete example: http://codepen.io/rarmatei/pen/apramB

var myIndex = 0;
var lastIndex = null;
var slides;
window.onload = function ()
{
slides = document.getElementsByClassName("mySlides");
slidePictures();
}
function slidePictures() {
slides[myIndex].style.display = "block";
slides[myIndex].className += " fadeIn";
console.log(slides[myIndex]);
setTimeout(function ()
{
slides[myIndex].className = "mySlides";
console.log(slides[myIndex]);
setTimeout(function ()
{
slides[myIndex].style.display = "none";
console.log("display none");
// Move indexes here
lastIndex = myIndex;
myIndex++;
}, 1000);
}, 2000);
if (myIndex >= 3)
return;
setTimeout(slidePictures, 4000);
}
.slidesDiv>img {
width: 80%;
height: 80%;
margin-left: 10%;
opacity: 0;
transition: opacity 1s;
}
.fadeIn {
opacity: 1 !important;
transition: opacity 1s;
}
<div class="slidesDiv">
<img class="mySlides" src="//placehold.it/200x80/0fb">
<img class="mySlides" src="//placehold.it/200x80/0bf">
<img class="mySlides" src="//placehold.it/200x80/fb0">
<img class="mySlides" src="//placehold.it/200x80/0fb">
<h1 id="indicator"> Indicator </h1>
</div>

It's pretty hard to tell what you're trying to achieve from your code. I assume that you want the pictures to fade in, and after a certain delay to fade out again?
For that I would highly suggest you to use jQuery. Here's a fiddle I made.
The slidePictures function would now just look like this:
function slidePictures() {
$(".mySlides").each(function(element){
console.log(this);
// 2000 is the duration of the fading in milliseconds
$(this).fadeIn(2000, function(){
// fadeout is delayed 4000 milliseconds
$(this).delay(4000).fadeOut(2000);
});
});
}
If that's not what you need, please provide additional information.
grwag

Related

Trying to make a transition with opacity on images

like my title says, I'm trying to make a transition with opacity (0 to 1 with 2secondes interval) on images, but I don't know how to make it.
The transition only works on the first image but not on the others, and I can't figure it out why.
So I hope you'll help me to understand my mistakes, I'm new on javascript. Thank you in advance, here my code
My HTML file :
<img src="img/1.jpg" alt="slide-photo">
My CSS file :
#slideshow-home img {
width: 100%;
opacity: 0;
transition: 1s ease-in-out;
}
My JS file :
var image = document.querySelector('img');
var img = 1 ;
window.setInterval(changeImage, 2000);
function changeImage() {
image.setAttribute('src', 'img/' + img + '.jpg');
image.style.opacity = 1;
img++;
if(img === 6) {
img = 1;
}
}
This is how i handle fade in transitions for images, the benefit is it doesn't start until the image has actually been loaded so it should never be choppy while fading in
JS
var image = document.querySelector('img');
var img = 1;
window.setInterval(changeImage,5000);
function changeImage() {
image.classList.remove('fadeIn')
image.src = 'img/'+img+'.jpg'
img++
if (img == 6) {
img = 1;
}
}
image.addEventListener('load', () => { // This function looks at the image and every time an image is loaded i.e whenever it gets a new src, it does a fade in animation
void(image.offsetHeight)
image.classList.add('fadeIn')
})
CSS
I normally do this with an animation, like below
#slideshow-home img {
width: 100%;
opacity: 0;
}
#keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
.fadeIn {
animation:fadeIn 2s forwards;
}

Fading background image with javascript on image switch

I have three images which my two div's switch between. However, the animation appears too rough. How do I apply a fade right before the switch?
<div class="my-images">
<div id="image-1"></div>
<div id="image-2"></div>
</div>
<script>
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("image-1").style.backgroundImage = images[x];
document.getElementById("image-2").style.backgroundImage = images[x];
}
function startTimer() {
setInterval(displayNextImage, 10000);
}
var images = [],
x = 0;
images[0] = "url('images/snow.jpeg')";
images[1] = "url('images/nike.jpeg')";
images[2] = "url('images/motor.jpeg')";
</script>
This loops continuously so I do not want it just fading in on the first load.
Without JQuery you'll have cross-browser compatibility issue.
So i suggest you to use JQuery to achieve this.
<div class="my-images">
<div class="my-image" id="image-1"></div>
<div class="my-image" id="image-2"></div>
</div>
<script>
function displayNextImage() {
$("#image-" + x).css('backgroundImage', images[x]).show('slow');
x++;
}
var images = [],
x = 0;
images[0] = "url('images/snow.jpeg')";
images[1] = "url('images/nike.jpeg')";
images[2] = "url('images/motor.jpeg')";
</script>
And you have to add this to css:
.my-image{
display:none;
}
In case you not use display: block to you element:
Your CSS will be:
.my-image{
display:whatYouWant;
}
Then need add the document ready() function and change show() to fadeIn():
$(document).ready(function(){
$(".my-image").hide();
});
function displayNextImage() {
$("#image-" + x).css('backgroundImage', images[x]).fadeIn('slow');
x++;
}
This will work because fadeIn() set to display the previous value.
If you want div visible before image adding, remove $(document).ready() call and edit displayNextImage():
function displayNextImage() {
$("#image-" + x).hide().css('backgroundImage', images[x]).fadeIn('slow');
x++;
}
You can do it with CSS animation, for each cycle:
1) swap the image sources like you are already doing
2) reset the fade in animation, more info here
3) increment your index
const imgs = [
'https://source.unsplash.com/iMdsjoiftZo/100x100',
'https://source.unsplash.com/ifhgv-c6QiY/100x100',
'https://source.unsplash.com/w5e288LU8SU/100x100'
];
let index = 0;
const oldImage1 = document.getElementById('oldImage1');
const newImage1 = document.getElementById('newImage1');
const oldImage2 = document.getElementById('oldImage2');
const newImage2 = document.getElementById('newImage2');
window.setInterval(() => {
// put new image in old image
oldImage1.src = newImage1.src;
oldImage2.src = newImage2.src;
// Set new image
newImage1.src = imgs[index];
newImage2.src = imgs[index];
// reset animation
newImage1.style.animation = 'none';
newImage1.offsetHeight; /* trigger reflow */
newImage1.style.animation = null;
newImage2.style.animation = 'none';
newImage2.offsetHeight; /* trigger reflow */
newImage2.style.animation = null;
// increment x
index = index + 1 >= imgs.length ? 0 : index + 1;
}, 1500);
.parent {
position: relative;
top: 0;
left: 0;
float: left;
}
.oldImage1 {
position: relative;
top: 0;
left: 0;
}
.newImage1 {
position: absolute;
top: 0;
left: 0;
}
.oldImage2 {
position: relative;
top: 0;
left: 100;
}
.newImage2 {
position: absolute;
top: 0;
left: 100;
}
.fade-in {
animation: fadein 1s;
}
#keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
<div class="parent">
<img id="oldImage1" class="oldImage1" src="https://source.unsplash.com/ifhgv-c6QiY/100x100" />
<img id="newImage1" class="newImage1 fade-in" src="https://source.unsplash.com/w5e288LU8SU/100x100" />
</div>
<div class="parent">
<img id="oldImage2" class="oldImage2" src="https://source.unsplash.com/ifhgv-c6QiY/100x100" />
<img id="newImage2" class="newImage2 fade-in" src="https://source.unsplash.com/w5e288LU8SU/100x100" />
</div>

Changing Text with Fade Javascript Multiple times

I am trying to create my own website, where it has an initial quote in the center:
"Welcome to my website", and when you hover over the menu options, the quote should change.
For example: if I hover over About it could say: "This is my About me Page". (The example is obviously simplified).
HTML Snippet:
About
Contact
Home
<div>
<p>
Welcome to my Website!
</p>
</div>
CSS Snippet:
.fade {
animation: fadein 2s;
}
#keyframes fadein {
from {
opacity:1;
}
50% {
opacity: 0;
}
to {
opacity:1;
}
}
JS Snippet
let myP = document.querySelector('p');
let titleWords = document.querySelector('a.titleAbout');
titleWords.addEventListener('mouseenter', function(){
myP.classList.add("fade");
setTimeout(function(){
myP.innerHTML = "This is my about Me page";
}, 1000);
setTimeout(function(){
text.classList.toggle("fade");
}, 2000);
});
titleWords = document.querySelector('a.titleContact');
titleWords.addEventListener('mouseenter', function(){
myP.classList.add("fade");
setTimeout(function(){
myP.innerHTML = "This is my Contact page";
}, 1000);
setTimeout(function(){
text.classList.toggle("fade");
}, 2000);
});
However - it only does the fade properly the first time I hover over a menu item, the other times it changes the innerHTML, but doesn't fade in and out.
Why exactly is this happening an how can I fix it?
you have not defined the text variable in your javascript. I think you mean myP.classList.toggle("fade");
let myP = document.querySelector('p');
let titleWords = document.querySelector('a.titleAbout');
titleWords.addEventListener('mouseenter', function(){
myP.classList.add("fade");
setTimeout(function(){
myP.innerHTML = "This is my about Me page";
}, 1000);
setTimeout(function(){
myP.classList.toggle("fade");
}, 2000);
});
titleWords = document.querySelector('a.titleContact');
titleWords.addEventListener('mouseenter', function(){
myP.classList.add("fade");
setTimeout(function(){
myP.innerHTML = "This is my Contact page";
}, 1000);
setTimeout(function(){
myP.classList.toggle("fade");
}, 2000);
});
.fade {
animation: fadein 2s;
}
#keyframes fadein {
from {
opacity:1;
}
50% {
opacity: 0;
}
to {
opacity:1;
}
}
About
Contact
Home
<div>
<p>
Welcome to my Website!
</p>
</div>
You can do it shorter and without setTimeout:
let myP = document.querySelector('p');
function show(textToShow){
myP.innerHTML = textToShow;
myP.classList.add("fade");
}
function hide(){
myP.classList.remove("fade");
}
.fade {
animation: fadein 3s;
}
#keyframes fadein {
from {
opacity:1;
}
50% {
opacity: 0;
}
to {
opacity:1;
}
}
About
Contact
Home
<div>
<p>
Welcome to my Website!
</p>
</div>
I have refactored your code to a more generic version, so you can have as many links as you want and do not need to repeat your code. It takes a title attribute from the a tag as text. Maybe this behaves more like you intended, you can play around uncommenting that timeout.
const myPContainer = document.getElementById('pContainer');
const titleWords = document.querySelectorAll('a');
let i;
function attachHandlers(i, elem) {
let timeoutHandle;
const pElem = document.createElement('p');
pElem.innerHTML = elem.getAttribute('title');
myPContainer.appendChild(pElem);
elem.addEventListener('mouseenter', function(){
timeoutHandle = null;
pElem.classList.add("fadein");
});
elem.addEventListener('mouseleave', function(){
// timeoutHandle = setTimeout(() => {
pElem.classList.remove("fadein");
// }, 2000);
});
}
for (i = 0; i < titleWords.length; ++i) {
attachHandlers(i, titleWords[i]);
}
#pContainer {
position: relative;
height: 20px;
}
#pContainer p {
position: absolute;
display: block;
opacity: 0;
}
.fadein {
animation: fadein 2s;
display: block;
}
#keyframes fadein {
from {
opacity: 0;
}
50% {
opacity: 1;
}
to {
opacity: 0;
}
}
About
Contact
Home
<div id="pContainer"></div>

setTimeOut without delay

The goal is for the pictures to transition into each other.
I started it off with the first picture having 1 opacity and the other three having a 0 opacity.
How could I go about making it start transitioning from the start and then continuing the transition loop every 12 seconds. I don't want to wait 12 seconds to start the transition
Here is my HTML with inline CSS
<img id="01BrunetteGirl" style="width:100%; opacity:1;" src="images/brunettesmiling.jpg" alt="">
<img id="02ManAndWife" style="width:100%; opacity:0;" src="images/manandwife.jpg" alt="" />
<img id="03GlassesMan" style="width:100%; opacity:0;" src="images/manwithglasses.jpg" alt="">
<img id="04BlondeGirl" style="width:100%; opacity:0;" src="images/blondegirlsmile.jpg" alt="" />
And here is my Javascript
<script>
$(document).ready(function() {
setInterval(function() {
setTimeout(function() {
document.getElementById("01BrunetteGirl").style.opacity = "0";
document.getElementById("02ManAndWife").style.opacity = "1";
document.getElementById("03GlassesMan").style.opacity = "0";
document.getElementById("04BlondeGirl").style.opacity = "0";
}, 3000);
setTimeout(function() {
document.getElementById("01BrunetteGirl").style.opacity = "0";
document.getElementById("02ManAndWife").style.opacity = "0";
document.getElementById("03GlassesMan").style.opacity = "1";
document.getElementById("04BlondeGirl").style.opacity = "0";
}, 6000);
setTimeout(function() {
document.getElementById("01BrunetteGirl").style.opacity = "0";
document.getElementById("02ManAndWife").style.opacity = "0";
document.getElementById("03GlassesMan").style.opacity = "0";
document.getElementById("04BlondeGirl").style.opacity = "1";
}, 9000);
setTimeout(function() {
document.getElementById("01BrunetteGirl").style.opacity = "1";
document.getElementById("02ManAndWife").style.opacity = "0";
document.getElementById("03GlassesMan").style.opacity = "0";
document.getElementById("04BlondeGirl").style.opacity = "0";
}, 12000);
}, 12000);
});
</script>
Change your code like below
var currentImageIndex = 0;
setInterval(function() {
var imageArrayIds = ["01BrunetteGirl", "02ManAndWife", "03GlassesMan", "04BlondeGirl"];
if(currentImageIndex > 3) {
currentImageIndex = 0;
}
for(var index in imageArrayIds) {
document.getElementById(imageArrayIds[index]).style.opacity = (currentImageIndex == index ? "1" : "0");
}
currentImageIndex++;
}, 3000);
Working Demo
Working Demo with jQuery animate effect
Late, and there's a good accepted answer, but you could build on Kundan's approach and automatically iterate through the images without first defining them in an array. Furthermore, by simply changing the image's classname instead we can move all the presentational properties such as opacity and the animation to the stylesheet thus allowing you to pick and choose the display and animation styles independently of the JavaScript.
View the jsFiddle or check out the snippet below.
Or check out this jsFiddle with different style and animation (but no change to JS)
var images = document.querySelectorAll("#images img"),
i=images.length-1;
(function next(){
i++;
images[i-1].className="";
if(i>=images.length){i=0;}
images[i].className="active";
setTimeout(function(){next();},3000);
})();
#images img{
position:absolute;
width:100%;
opacity:0;
transition: all 1.0s;
-moz-transition: all 1.0s;
-webkit-transition: all 1.0s;
-webkit-transform:rotate(180deg) scale(0.2);
transform:rotate(180deg) scale(0.2);
}
#images img.active {
opacity:1;
-webkit-transform:rotate(0deg) scale(1);
transform:rotate(0deg) scale(1);
}
<div id="images">
<img src="http://www.placehold.it/200&text=brunettesmiling.jpg" alt="brunette smiling" />
<img src="http://www.placehold.it/200&text=manandwife.jpg" alt="man and wife" />
<img src="http://www.placehold.it/200&text=manwithglasses.jpg" alt="man with glasses" />
<img src="http://www.placehold.it/200&text=blondegirlsmile.jpg" alt="blonde girl smile" />
</div>
FYI. You can do this entirely in CSS. I wouldn't recommend it but its there as an option.
You can set a very small initial delay-time (e.g. 100) and set it to your desired delay-time within the function:
var delay = 100;
function foo() {
document.getElementById("01BrunetteGirl").style.opacity = "1";
document.getElementById("02ManAndWife").style.opacity = "0";
document.getElementById("03GlassesMan").style.opacity = "0";
document.getElementById("04BlondeGirl").style.opacity = "0";
delay = 12000;
setTimeout(foo, delay);
}

How do I make a simple fade effect on an image slider with javascript(only)?

I'm using the following code to run a slider. The function runs well.
How do I make a simple fadein effect with js. No jQuery.
Also setInterval waits 5 seconds before displaying the first image. How do I start with an image and then continue with the 5 second interval?
var i = 0;
var hello = function(){
if(i<image.length)
{document.getElementById('fullscreenImage').src = image[i];
i+=1;
}
else i = 0;
}
setInterval(hello,5000);
#fullscreenImage {
z-index: -999;
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
background-size: cover;
}
<img id="fullscreenImage"></img>
You can do this by progressively adjusting the opacity style property of an image. Here's a simple example: declare some HTML structure, then wire the sliding behavior, using the makeSlider() function, passing an array containing the target images, as well as fading parameters.
HTML file example (whatever.html) :
<head>
<style type="text/css">
img {
position: absolute;
top: 0;
left: 0;
width: 300px;
visibility: hidden;
}
img:first-child {
visibility: visible;
}
</style>
<script type="text/javascript" src="slider.js"></script>
</head>
<body>
<img src="1.jpg" alt="Alt 1" />
<img src="2.jpg" alt="Alt 2" />
<script type="text/javascript">
var fadeInterval = 3000;
var fadeStep = 20;
setTimeout(function() {
makeSlider([document.images[0], document.images[1]], fadeInterval, fadeStep);
}, fadeInterval);
</script>
</body>
Javascript file (slider.js):
function makeSlider(pictures, fadeInterval, fadeStep) {
var currentIndex = 0;
function show() {
var nextIndex = (currentIndex + 1) % pictures.length;
var current = pictures[currentIndex];
var next = pictures[nextIndex];
fade(current, 1, -0.1, function() {
current.style.visibility = "hidden";
next.style.visibility = "visible";
fade(next, 0, +0.1, function() {
currentIndex = nextIndex;
setTimeout(function() { show(); }, fadeInterval);
});
});
}
function fade(element, origin, step, continuation) {
element.style.opacity = origin;
setTimeout(function () {
var nextOrigin = Math.round((origin + step) * 10) / 10;
if (nextOrigin >= 0 && nextOrigin <= 1) {
fade(element, nextOrigin, step, continuation);
} else {
continuation();
}
}, fadeStep);
}
show();
}
HTH.

Categories

Resources