How to Fade-in 2 images simultaneously using JS? - javascript

Already tried answer - jQuery Fade Images simultaneously
I have 2 divisions with 2 different images and i want them to load after i scroll down to that section, only 1 image is fading-in after i apply the same function to both images.
var opacity = 0;
var intervalID = 0;
window.onload = fadeIn;
function fadeIn()
{
setInterval(show, 200);
}
function show()
{
var star11 = document.getElementById("star1");
opacity = Number(window.getComputedStyle(star11).getPropertyValue("opacity"));
if (opacity < 1)
{
opacity = opacity + 0.1;
star11.style.opacity = opacity
}
else
{
clearInterval(intervalID);
}
}
var opacity = 0;
var intervalID = 0;
window.onload = fadeIn;
function fadeIn()
{
setInterval(show, 200);
}
function show()
{
var star22 = document.getElementById("star2");
opacity = Number(window.getComputedStyle(star22).getPropertyValue("opacity"));
if (opacity < 1)
{
opacity = opacity + 0.1;
star22.style.opacity = opacity
}
else
{
clearInterval(intervalID);
}
}
#star1{
opacity:0;
width:100px;
height:100px;
float:left;
}
#star2{
opacity:0;
width:100px;
height:100px;
float:right;
}
<div>
<img id="star1" src="https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/socialmedia/apple/271/star_2b50.png" alt="star123">
</div>
<div>
<img id="star2" src="https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/socialmedia/apple/271/star_2b50.png" alt="123star">
</div>
P.S - I am new to JS/JQuery.
Thank You

You are declaring the function show twice. So ehat happens here is that the first function that you defined for the first star will be over written by the second function written for the second star and hence the styles for the second star only works. Function defenition is just like variable assigning. The variable name taks the latest value for which that is assigned and will neglect the previous values when define multiple times.
So what I suggest is to decalre the function only once and pass the id as a parameter.
var opacity = 0;
var intervalID = 0;
window.onload = fadeIn;
function fadeIn() {
setInterval(() => show('star1'), 200);
setInterval(() => show('star2'), 200);
}
function show(starId) {
var star = document.getElementById(starId);
opacity = Number(
window.getComputedStyle(star).getPropertyValue("opacity")
);
if (opacity < 1) {
opacity = opacity + 0.1;
star.style.opacity = opacity;
} else {
clearInterval(intervalID);
}
}
#star1 {
opacity: 0;
width: 100px;
height: 100px;
float: left;
}
#star2 {
opacity: 0;
width: 100px;
height: 100px;
float: right;
}
<div>
<img
id="star1"
src="https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/socialmedia/apple/271/star_2b50.png"
alt="star123"
/>
</div>
<div>
<img
id="star2"
src="https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/socialmedia/apple/271/star_2b50.png"
alt="123star"
/>
</div>
Update
Handling scroll events.
I have refered this answer to prepare the javascript/jquery solution for scroll
$(document).ready(function () {
$(window).scroll(function () {
console.log("Scroll");
triggerScrollListner("star1");
triggerScrollListner("star2");
});
});
function triggerScrollListner(id) {
var hT = $(`#${id}`).offset().top,
hH = $(`#${id}`).outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > hT + hH - wH) {
setInterval(() => show(id), 200);
}
}
var opacity = 0;
var intervalID = 0;
function show(starId) {
var star = document.getElementById(starId);
opacity = Number(
window.getComputedStyle(star).getPropertyValue("opacity")
);
if (opacity < 1) {
opacity = opacity + 0.1;
star.style.opacity = opacity;
} else {
clearInterval(intervalID);
}
}
body {
height: 1000px;
}
#star1 {
opacity: 0;
width: 100px;
height: 100px;
float: left;
}
#star2 {
opacity: 0;
width: 100px;
height: 100px;
float: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div>
<img
id="star1"
src="https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/socialmedia/apple/271/star_2b50.png"
alt="star123"
/>
</div>
<div>
<img
id="star2"
src="https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/socialmedia/apple/271/star_2b50.png"
alt="123star"
/>
</div>
More generic solution with multiple stars
Since there was only one row, the visualiztion is a little hard. In this example I have added multiple rows and have made a little bit more visual.
$(document).ready(function () {
$(window).scroll(function () {
triggerScrollListner("star1");
triggerScrollListner("star2");
triggerScrollListner("star3");
triggerScrollListner("star4");
});
});
function triggerScrollListner(id) {
var hT = $(`#${id}`).offset().top,
hH = $(`#${id}`).outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > hT + hH - wH) {
setInterval(() => show(id), 200);
}
}
var opacity = 0;
var intervalID = 0;
function show(starId) {
var star = document.getElementById(starId);
opacity = Number(
window.getComputedStyle(star).getPropertyValue("opacity")
);
if (opacity < 1) {
opacity = opacity + 0.1;
star.style.opacity = opacity;
} else {
clearInterval(intervalID);
}
}
.star {
opacity: 0;
width: 100px;
height: 100px;
}
.container1, .container2 {
display: flex;
width: 100%;
flex-direction: column;
justify-content: space-between;
flex-direction: row;
}
.container2 {
margin-top: 1500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div class="container1">
<img
id="star1"
class="star"
src="https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/socialmedia/apple/271/star_2b50.png"
alt="star123"
/>
<img
id="star2"
class="star"
src="https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/socialmedia/apple/271/star_2b50.png"
alt="123star"
/>
</div>
<div class="container2">
<img
id="star3"
class="star"
src="https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/socialmedia/apple/271/star_2b50.png"
alt="star123"
/>
<img
id="star4"
class="star"
src="https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/socialmedia/apple/271/star_2b50.png"
alt="123star"
/>
</div>

Just fiddled around into the code
Needed only 1 function and changed code in js only.
var opacity = 0;
var intervalID = 0;
window.onload = fadeIn;
function fadeIn()
{
setInterval(show, 200);
}
function show()
{
var star11 = document.getElementById("star1");
var star22 = document.getElementById("star2");
opacity =
Number(window.getComputedStyle(star22).getPropertyValue("opacity"));
opacity =
Number(window.getComputedStyle(star11).getPropertyValue("opacity"));
if (opacity < 1)
{
opacity = opacity + 0.1;
star11.style.opacity = opacity
star22.style.opacity = opacity
}
else
{
clearInterval(intervalID);
}
}

Related

JavaScript and CSS Carousel/Slideshow with z-index

I need to make a carousel/slideshow in plain JavaScript mixed with CSS that slides through the images one by one loop seamlessly.
I can't seem to get any code working. I've tried several approaches but can't. It's got to be with z-index, and not making use of flex.
This is my third attempt at coding this. Can't seem to get the logic. It has to have navigation buttons to switch between images. Can someone help me out?
const getHeader = document.querySelector('.wp-custom-header');
const getImages = document.querySelectorAll('.wp-custom-header img');
const computeImages = function () {
getImages.forEach((img, index) => {
if (index > 0) img.classList.add('out');
});
};
computeImages();
let counter = 0;
let reinit = false;
// getHeader.classList.add('transformSlide');
const slideShowTimer = setInterval(() => {
if (counter > 0 && counter < getImages.length - 1) {
getImages[counter + 1].classList.add('transform-slide');
getImages[counter + 1].classList.add('onqueue-current');
getImages[counter + 1].classList.remove('out');
} else if (counter === 0 && reinit === false) {
getImages[counter + 1].classList.add('transform-slide');
getImages[counter + 1].classList.add('onqueue-current');
getImages[counter + 1].classList.remove('out');
} else if (counter === 0 && reinit === true) {
getImages[counter].classList.add('transform-slide');
getImages[counter].classList.add('onqueue-current');
getImages[counter].classList.remove('out');
getImages[getImages.length - 1].classList.add('out');
getImages[getImages.length - 1].classList.remove('transform-slide');
getImages[getImages.length - 1].classList.remove('onqueue-current');
}
counter++;
}, 2000);
getHeader.addEventListener('transitionend', () => {
if (counter >= 1) {
if (!reinit) {
getImages[counter - 1].classList.remove('transform-slide');
getImages[counter - 1].classList.remove('onqueue-current');
getImages[counter - 1].classList.add('out');
} else {
getImages[counter].classList.remove('transform-slide');
getImages[counter].classList.remove('onqueue-current');
getImages[counter].classList.add('out');
}
}
if (counter >= getImages.length - 1) {
console.log(counter);
counter = 0;
reinit = true;
}
});
This is the HTML
<div id="wp-custom-header" class="wp-custom-header">
<img alt="" src="./image01.svg" />
<img alt="" src="./image02.svg" />
<img alt="" src="./image03.svg" />
<img alt="" src="./image04.svg" />
<img alt="" src="./image05.svg" />
<img alt="" src="./image06.svg" />
</div>
The CSS
.wp-custom-header {
position: relative;
display: block;
width: 100%;
height: var(--header-size);
}
.wp-custom-header img {
position: absolute;
display: block;
min-width: 100%;
-o-object-fit: cover;
object-fit: cover;
transition: var(--slide-transform) ease-in-out;
}
.wp-custom-header img.out {
/* left: -450px; */
z-index: 0;
transform: translateX(100%);
}
.wp-custom-header img.onqueue-next {
z-index: 0;
left: 0px;
}
.wp-custom-header img.onqueue-current {
z-index: 1;
transform: translateX(0px);
}
.transform-slide {
transition: var(--slide-transform) ease-in-out;
}
I took the liberty to tinker with your code. I've reworked your code into smaller functions and added a looping mechanic. Now you have buttons that will loop infinitely no matter how many slides there are in your carousel.
I've added a previous and a next button. Hovering over the images will stop the autoslide functionality from running so that you can control going to the next and previous slide. Whenever you stop hovering the carousel continues.
Hope that this is what you were looking for.
const header = document.querySelector('.wp-custom-header');
const images = document.querySelectorAll('.wp-custom-header img');
const buttons = document.querySelectorAll('.wp-custom-header button');
let activeSlideIndex = 0;
let interval = null;
const updateCarousel = () => {
images.forEach((image, index) => {
if (index === activeSlideIndex) {
image.classList.add('active');
} else if (image.classList.contains('active')) {
image.classList.remove('active');
}
});
};
const nextSlide = () => {
if (activeSlideIndex + 1 < images.length) {
activeSlideIndex++;
} else {
activeSlideIndex = 0;
}
};
const prevSlide = () => {
if (activeSlideIndex - 1 >= 0) {
activeSlideIndex--;
} else {
activeSlideIndex = images.length - 1;
}
};
const startInterval = () => setInterval(() => {
nextSlide();
updateCarousel();
}, 2000);
const stopInterval = () => {
clearInterval(interval);
interval = null;
};
interval = startInterval();
const controls = {
'prev': prevSlide,
'next': nextSlide
};
header.addEventListener('mouseenter', () => {
if (interval !== null) {
stopInterval();
}
});
header.addEventListener('mouseleave', () => {
interval = startInterval();
});
buttons.forEach(button => {
button.addEventListener('click', event => {
const value = event.target.value;
const action = controls[value];
action();
updateCarousel();
});
});
.wp-custom-header {
position: relative;
}
.wp-custom-header-images {
display: block;
width: 100%;
height: 250px;
}
.wp-custom-header-images img {
position: absolute;
display: block;
width: 100%;
height: 100%;
-o-object-fit: cover;
object-fit: cover;
opacity: 0;
will-change: opacity;
transition: opacity 250ms ease-in-out;
z-index: 0;
}
.wp-custom-header-images img.active {
z-index: 1;
opacity: 1;
}
.wp-custom-header-button {
position: absolute;
top: 50%;
border: 1px solid #d0d0d0;
background-color: #f0f0f0;
border-radius: 50%;
width: 50px;
height: 50px;
cursor: pointer;
transform: translate(0, -50%);
z-index: 2;
}
.wp-custom-header-button[value="prev"] {
left: 15px;
}
.wp-custom-header-button[value="next"] {
right: 15px;
}
<div id="wp-custom-header" class="wp-custom-header">
<button class="wp-custom-header-button" value="prev">Prev</button>
<div class="wp-custom-header-images">
<img alt="" src="https://picsum.photos/seed/a/640/360" class="active" />
<img alt="" src="https://picsum.photos/seed/b/640/360" />
<img alt="" src="https://picsum.photos/seed/c/640/360" />
<img alt="" src="https://picsum.photos/seed/d/640/360" />
<img alt="" src="https://picsum.photos/seed/e/640/360" />
<img alt="" src="https://picsum.photos/seed/f/640/360" />
</div>
<button class="wp-custom-header-button" value="next">Next</button>
</div>

Javascript - how to trigger a "if" condition by a change through CSS

I'm being tormented in the past 4 hours to find out how to do this, I don't know what I'm doing wrong, I have a page with multiple layers, I wish to trigger some transition when the needed page has opacity 1, it should be simple when u think of it, here is my code, please help ;)
slide1 = document.querySelector('.slide1');
function videoPlay() {
var videoOne = document.getElementById('myVideo');
if ((slide1.style.opacity) > 0 ) {
videoOne.play();
}
}
videoPlay();
.slide {
width: 100%;
background-size: cover;
background-position: center;
position: absolute;
}
.slide1 {
width: 100%;
background: none;
opacity: 0;
}
<div class="slide slide1">
<div class="slide-content">
<div class="secondColumn">
<video muted id="myVideo">
<source src="Media/Acqua.mp4" type="video/mp4">
</video>
<div class="lowerTab"></div>
</div>
</div>
here is the code which i use to change the opacity using the wheel :
//wheel event
document.addEventListener('wheel',
function scrollWheel(event) {
var fig =event.deltaY;
if (fig > 0) {
slideMove();
}
else if (fig<0) {
slideMovReverse();
}
})
//basic movement
function slideMove() {
if (current === sliderImages.length-1 ) {
current = -1
}
reset();
sliderImages[current+1].style.transition = "opacity 1s ease-in 0s";
sliderImages[current+1].style.opacity= "1.0";
current++;
}
You can use the transitionend event, but you'd have to set up the transition first. As it sits now, there's not much information in your question about the different slides, how the transitions are set up, etc. Here's a baseline to give you an idea:
const slide1 = document.querySelector('.slide1');
const videoEl = document.querySelector('.slide1__video');
const button = document.querySelector('button');
let inView = false;
slide1.addEventListener('transitionend', () => {
let content = 'Playing';
if (inView) {
content = ''
}
videoEl.textContent = content;
inView = !inView;
})
button.addEventListener('click', () => {
slide1.classList.toggle('active')
})
.slide1 {
transition: opacity 500ms linear;
opacity: 0;
border: 1px solid green;
padding: 10px;
margin-bottom: 24px
}
.slide1.active {
opacity: 1
}
<div class="slide1">
Slide 1
<div class="slide1__video"></div>
</div>
<button>Next</button>
Edit
It'll need some love but I think it's in the right direction to what you're after.
const slides = Array.from(document.querySelectorAll('.slide'));
document.addEventListener('wheel', onScroll);
const SCROLL_TOLERANCE = 100;
let currentIndex = 0;
let currentScroll = 0;
function onScroll(e) {
if (e.deltaY > 0) {
currentScroll += 1;
} else {
currentScroll -= 1;
}
if (currentScroll >= (currentIndex * SCROLL_TOLERANCE) + 15) {
showNext();
} else if (currentScroll <= (currentIndex * SCROLL_TOLERANCE) - 15) {
showPrevious();
}
}
function showNext() {
if (currentIndex === slides.length - 1) {
return console.warn('At the end.');
}
currentIndex += 1;
setSlide();
}
function showPrevious() {
if (currentIndex === 0) {
return console.warn('At the beginning.');
}
currentIndex -= 1;
setSlide();
}
function setSlide() {
let newOpacity = 0;
slides.forEach(slide => {
if (+slide.dataset.index === currentIndex) {
newOpacity = 1
} else {
newOpacity = 0;
}
slide.style.opacity = newOpacity;
slide.addEventListener('transitionend', () => {
console.log('Done transitioning!');
// Do things here when the transition is over.
})
});
}
html,
body {
padding: 0;
margin: 0;
font-family: sans-serif;
font-size: 18px
}
.slide {
border: 3px solid #efefef;
position: absolute;
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
transition: all 500ms linear;
opacity: 0;
transition-delay: 250ms;
}
.slide.active {
opacity: 1;
}
<div class="slide active" data-index="0">
Slide 1
</div>
<div class="slide" data-index="1">
Slide 2
</div>
<div class="slide" data-index="2">
Slide 3
</div>
<div class="slide" data-index="3">
Slide 4
</div>

How to crossfade images in .js slideshow

So this is my slideshow div:
<div class="header">
<img name="slide" class="slide">
</div>
the css for it:
.slide{
width: 80%;
height: auto;
filter: brightness(90%);
}
and the javascript:
var i = 0;
var images = [];
var time = 4000;
images[0] = '1.png';
images[1] = '2.png';
images[2] = '3.png';
function changeImg() {
document.slide.src = images[i];
if (i < images.length -1) {
i++;
}
else
{
i = 0;
}
setTimeout("changeImg()", time);
}
window.onload = changeImg;
Now i want it to crossfade, currently its just switching the images very abruptly, but i want it smooth.
Any help?
You need to add opacity set to 0 on your css class, and then create a new class with opacity set to 1, that way you'll trigger the function to switch opacity after a specific time period has passed
<style>
.slide {
border: none;
opacity: 0;
position: absolute;
top: 0;
left: 0;
-webkit-transition: opacity 2s linear;
-moz-transition: opacity 2s linear;
-o-transition: opacity 2s linear;
transition: opacity 2s linear;
}
.visible {
opacity: 1;
}
</style>
<div class="header">
<img id="img0" class="slide visible" src="1.png">
<img id="img1" class="slide" src="2.png">
<img id="img2" class="slide" src="3.png">
</div>
<script>
var actual = 0;
var total = 3;
function addClass(elem, name) {
elem.className = elem.className + " " + name;
}
function deleteClass(elem, name) {
var c = elem.className;
elem.className = c.replace(name, "").replace(/ /g, " ").replace(/^ | $/g, "");
}
function nextImg() {
var e;
e = document.getElementById("img" + actual);
deleteClass(e, "visible");
actual++;
if (actual > total - 1) actual = 0;
e = document.getElementById("img" + actual);
addClass(e, "visible");
}
var slider = setInterval(nextImg, 4000);
</script>
While I like Joe's answer, here is one that uses JavaScript without adding or removing classes:
I gave the <img> an id for ease of reference here:
<img id='slideShow' name="slide" class="slide">
JavaScript:
function fadeImg(elem, total, step, speed){
step=step||5;
speed=speed||50;
var iter=0;
var fadeOutTime=(100/step)*speed;
var time=total;
var n = 0;
var opacity;
elem.src=images[n];
var fadeInterval=setInterval(function(){
time=time-speed;
opacity=iter/100;
if(time>fadeOutTime&&opacity<1){
iter=iter+step;
} else if(time<=fadeOutTime&&time>0&&opacity>0){
iter=iter-step;
} else if(time<=0){
n<images.length-1?n++:n=0;
elem.src=images[n];
time=total;
}
elem.style.opacity=opacity;
elem.style.filter= 'alpha(opacity=' +opacity*100 + ')';
},speed);
}
window.onload = fadeImg(document.getElementById('slideShow'),time);
I borrowed the interval concept from here: https://stackoverflow.com/a/2207751/6661052

How to speed up fadein / fadeout

I'm using the following code to fadein/fadeout images every second which works fine but I would like to fade the images in and out every 1/2 second. I can change the setInterval to 500 but this simply causes a bit of a mess. I clearly need to redfine fadein and fadeout.
I have bootstrap loaded so I'm guessing the functions are defined within the bootstrap js but how do I respecify their timing?
var $els = $('div[id^=image]'),
i = 0,
len = $els.length;
var start = 1;
var end = 999999999999999;
jQuery(function () {
$els.slice(1).hide();
spin = setInterval(function () {
$els.eq(i).fadeOut(function () {
i = Math.floor(Math.random() * len);
$els.eq(i).fadeIn();
});
start = new Date().getTime();
if (start > end) {
clearInterval(spin);
}
}, 1000);
{% for m in myusers %}
if (i == {{ forloop.counter0 }}) { document.getElementById('name{{ forloop.counter0 }}').style.display = 'Block';}
{% endfor %}
});
Since you are using jQuery, why not use fadeOut/fadeIn or fadeToggle?
$(document).ready(function() {
setInterval(function() {
$('.a1, .a2').stop().fadeToggle(500);
}, 500);
});
.wrapper {
position: relative;
width: 100px;
height: 100px;
margin: 1px;
display: inline-block;
}
.a1,
.a2 {
position: absolute;
left: 0;
top: 0;
width: 100px;
height: 100px;
background-color: blue;
}
.a2 {
display: none;
background-color: red;
}
.wrapper2 .a1 {
display: none;
}
.wrapper2 .a2 {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="a1"></div>
<div class="a2"></div>
</div>
<div class="wrapper wrapper2">
<div class="a1"></div>
<div class="a2"></div>
</div>
var box = document.getElementById('box');
function fadeOutIn(elem, speed ) {
if (!elem.style.opacity) {
elem.style.opacity = 1;
} // end if
var outInterval = setInterval(function() {
elem.style.opacity -= 0.02;
if (elem.style.opacity <= 0) {
clearInterval(outInterval);
var inInterval = setInterval(function() {
elem.style.opacity = Number(elem.style.opacity)+0.02;
if (elem.style.opacity >= 1)
clearInterval(inInterval);
}, speed/50 );
} // end if
}, speed/50 );
} // end fadeOut()
fadeOutIn(box, 2000 );
Hello please see my solution . It is your helpful or not.
Thanks.

Javascript Slider doesn't work correctly with transition end

I don't know why people's are not answering this question.I'm making a horizontal infinite loop slider. What approach i'm using is making a ul container which has 3 images, for example if there are 3 images then clone the first image and place it to the end of the slider, same with last image make clone and place it before the first image. So now total images are 5. Default slider translation always start from first image not from clone one. Here is an example. What i'm facing is, I want to reset the slider after slider comes to the last clone image with same continuous loop like a carousel slider. I try using addEventListener with the event name transitionend but that event doesn't perform correctly and showing unsatisfied behavior. Is there a way to fix this?
(function () {
var resetTranslation = "translate3d(-300px,0px,0px)";
var elm = document.querySelector('.Working');
elm.style.transform = resetTranslation;
var arr = document.querySelectorAll('.Working li');
var clonefirst,
clonelast,
width = 300;
index = 2;
clonefirst = arr[0].cloneNode(true);
clonelast = arr[arr.length - 1].cloneNode(true);
elm.insertBefore(clonelast, arr[0]);
arr[arr.length - 1].parentNode.insertBefore(clonefirst, arr[arr.length - 1].nextSibling);
//Update
arr = document.querySelectorAll('.Working li');
elm.style.transition = 'transform 1.5s ease';
setInterval(function () {
elm.style.transform = 'translate3d(-' + index * width + 'px,0px,0px)';
if (index == arr.length - 1) {
elm.addEventListener('transitionend', function () {
elm.style.transform = resetTranslation;
});
index = 1;
}
index++;
}, 4000)
})();
*{
box-sizing: border-box;
}
.wrapper{
position: relative;
overflow: hidden;
height: 320px;
width: 300px;
}
.Working{
list-style: none;
margin: 0;
padding: 0;
position: relative;
width: 3125%;
}
.Working li{
position: relative;
float: left;
}
img{
max-width: 100%;
display: block;
}
.SubContainer:after{
display: table;
clear: both;
content: "";
}
<div class="wrapper">
<ul class="SubContainer Working">
<li> <img class="" src="http://i.imgur.com/HqQb9V9.jpg" /></li>
<li><img class="" src="http://i.imgur.com/PMBBc07.jpg" /></li>
<li><img class="" src="http://i.imgur.com/GRrGSxe.jpg" /></li>
</ul>
</div>
I've messed around with your code to hack in a fix: https://jsfiddle.net/rap8o3q0/
The changed part:
var currentItem = 1;
setInterval(function () {
var getWidth = window.innerWidth;
if(len === currentItem){
i = 1;
currentItem = 1;
} else {
currentItem++;
i++;
}
var val = 'translate3d(-' + (i-1) * getWidth + 'px,0px,0px)';
UnorderedListElement.style.transform = val;
}, 3000);
Your transition end event is not immediately fire because last transition doesn't computed when last clone image appear. You can easily achieve this thing by using setTimeout function and pass number of milliseconds to wait, after that reset the translation. I don't know it's an efficient solution but i think its easily done by using this function.
Now I'm fixing your code with this.
(function () {
var elm = document.querySelector('.Working');
var arr = document.querySelectorAll('.Working li');
var clonefirst,
clonelast,
width = 300;
index = 2;
clonefirst = arr[0].cloneNode(true);
clonelast = arr[arr.length - 1].cloneNode(true);
elm.insertBefore(clonelast, arr[0]);
arr[arr.length - 1].parentNode.insertBefore(clonefirst, arr[arr.length - 1].nextSibling);
//Update
arr = document.querySelectorAll('.Working li');
setInterval(function () {
$(elm).css({
'transform': 'translate3d(-' + (index * width) + 'px,0px,0px)',
'transition': 'transform 1.5s ease'
});
if (index == arr.length - 1) {
setTimeout(function () {
$(elm).css({'transform': 'translate3d(-300px,0px,0px)', 'transition': 'none'});
index = 1;
}, 1400);
}
index++;
}, 2000)
})();
* {
box-sizing: border-box;
}
.wrapper {
position: relative;
overflow: hidden;
height: 320px;
width: 300px;
margin-top: 8px;
}
.Working {
list-style: none;
margin: 0;
padding: 0;
position: relative;
transform: translateX(-300px);
width: 3125%;
}
.Working li {
position: relative;
float: left;
}
img {
max-width: 100%;
display: block;
}
.SubContainer:after {
display: table;
clear: both;
content: "";
}
#checkboxer:checked + .wrapper {
overflow: visible;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="checkboxer">Remove Overflow Hidden</label>
<input type="checkbox" id="checkboxer" name="checkboxer"/>
<div class="wrapper">
<ul class="SubContainer Working">
<li> <img class="" src="http://i.imgur.com/HqQb9V9.jpg" /></li>
<li><img class="" src="http://i.imgur.com/PMBBc07.jpg" /></li>
<li><img class="" src="http://i.imgur.com/GRrGSxe.jpg" /></li>
</ul>
</div>
To come back your slider in its first position, you need to trigger a transition end event after the last (3th) translation, That works only one time.
$(UnorderedListElement).one("webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend", function ()
{
{
$(UnorderedListElement).css('transform', 'translate3d(0, 0, 0)');
}
});
But you need to make it to translate immediately. In link below you can see my slider that is very similar to yours, but works by absolute positioning and change the left property instead of transform.
Slider
Last thing: It is not a good idea to slide the hole of the image container. You must slide your images separately. In your way there is an obvious problem: When the page is sliding out the last image, there is not the next image to push it!
You can update your setInterval as
setInterval(function() {
var getWidth = window.innerWidth;
var val = 'translate3d(-' + i * getWidth + 'px,0px,0px)';
UnorderedListElement.style.transform = val;
i++;
if (i == 3) { //assuming three images here
i = 0
}
}, 3000)
var DomChanger;
(function() {
var listItem = document.querySelectorAll('.ah-slider li');
var len = listItem.length;
var getImage = document.querySelector('.ah-slider li img');
var UnorderedListElement = document.querySelector('.ah-slider');
var outerDiv = document.querySelector('.Slider');
UnorderedListElement.setAttribute('style', 'width:' + (len * 1000 + 215) + '%');
var i = 1;
DomChanger = function() {
for (var i = 0; i < len; ++i) {
listItem[i].setAttribute('style', 'width:' + window.innerWidth + 'px');
}
outerDiv.setAttribute('style', 'height:' + getImage.clientHeight + 'px');
};
setInterval(function() {
var getWidth = window.innerWidth;
var val = 'translate3d(-' + i * getWidth + 'px,0px,0px)';
UnorderedListElement.style.transform = val;
i++;
if (i == 3) {
i = 0
}
}, 3000)
})();
window.onload = function() {
DomChanger();
};
window.onresize = function() {
DomChanger();
};
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
padding: 0;
background-color: #fff;
}
.Slider {
width: 100%;
margin: 50px 0 0;
position: relative;
overflow: hidden;
}
.ah-slider {
padding: 0;
margin: 0;
list-style: none;
position: relative;
transition: transform .5s ease;
}
.ah-slider li {
position: relative;
float: left;
}
.ah-slider li img {
max-width: 100%;
display: block;
}
.clearFix:after {
content: "";
display: table;
clear: both;
}
<div class="Slider">
<ul class="ah-slider clearFix">
<li>
<img class="" src="http://i.imgur.com/L9Zi1UR.jpg" title="" />
</li>
<li>
<img class="" src="http://i.imgur.com/FEcEwFs.jpg" title="" />
</li>
<li><img class="" src=http://i.imgur.com/hURSKNa.jpg" title="" /></li>
</ul>
</div>

Categories

Resources