Last slide overlaps first at the end of the slideshow - javascript

I've set up a simple slideshow with a parallax effect where the queued slide overlaps the current slide. All works great until the slideshow cycle completes where the last slide misbehaves and does not reset its position underneath the current slide like the rest do. I cannot determine why it behaves like this.
JSFiddle
var slides = [];
// Append images to the slides array
$('.slide').each(function() {
"use strict";
slides.push($(this));
});
function slideshow() {
"use strict";
var $current = slides[0],
$next = slides[1];
setInterval(function() {
// Slide animation
$current.css('transform', 'translate3d(-30%, 0, 0)');
$next.css('transform', 'translate3d(0, 0, 0)');
// Reorder slides
slides.push($current);
slides.shift();
// Reestablish slide variables
$current = slides[0];
$next = slides[1];
// Reset position of slide
setTimeout(function() {
slides[3].css('transform', 'translate3d(100%, 0, 0)');
setTimeout(function() {
slides[3].css('z-index', 1);
}, 1000);
$current.css('z-index', 0);
}, 1000); // END: setTimeout()
}, 4000); // END: setInterval()
} // END: slideshow()
slideshow();
#charset "UTF-8";
/* CSS Document */
body {
margin: 0;
padding: 0;
}
#main-container {
height: 60vh;
width: 100vw;
overflow: hidden;
}
#slide-container {
width: 200vw;
height: 100%;
position: relative;
}
.slide {
background-position: center;
background-size: cover;
width: 50%;
height: 100%;
position: absolute;
transform: translate3d(100%, 0, 0);
z-index: 1;
transition: 1s cubic-bezier(.48, .14, .31, .97);
color: white;
line-height: 60vh;
text-align: center;
font-size: 70px;
}
#slide-1 {
background-image: url(https://media.mnn.com/assets/images/2015/03/forest-path-germany.jpg.653x0_q80_crop-smart.jpg);
transform: translate3d(0, 0, 0);
z-index: 0;
}
#slide-2 {
background-image: url(https://media.treehugger.com/assets/images/2016/03/woodland_trail.jpg.662x0_q70_crop-scale.jpg);
}
#slide-3 {
background-image: url(http://sim02.in.com/4fc598f2c9f2c0cdc5e0decc188d8d10_ft_xl.jpg);
}
#slide-4 {
background-image: url(https://media-cdn.tripadvisor.com/media/photo-s/05/fc/88/f9/waterloop-trail.jpg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main-container">
<div id="slide-container">
<div class="slide" id="slide-1">Slide 1</div>
<div class="slide" id="slide-2">Slide 2</div>
<div class="slide" id="slide-3">Slide 3</div>
<div class="slide" id="slide-4">Slide 4</div>
</div>
</div>

Place slides[3].css('z-index', -1) just be for the end of your setInterval. This will send the slide behind Slide1 so it doesn't reposition in the front.
When the slide is repositioned slide 1 has a z-index of 0 and slide 4 has a z-index of 1 as it is the current slide. So when is repositioned it is the forward most element. By changing the z-index it sends it to the back of the slides and then the rest of the script runs as it should.
var slides = [];
// Append images to the slides array
$('.slide').each(function() {
"use strict";
slides.push($(this));
});
function slideshow() {
"use strict";
var $current = slides[0],
$next = slides[1];
setInterval(function() {
// Slide animation
$current.css('transform', 'translate3d(-30%, 0, 0)');
$next.css('transform', 'translate3d(0, 0, 0)');
// Reorder slides
slides.push($current);
slides.shift();
// Reestablish slide variables
$current = slides[0];
$next = slides[1];
// Reset position of slide
setTimeout(function() {
slides[3].css('transform', 'translate3d(100%, 0, 0)');
setTimeout(function() {
slides[3].css('z-index', 1);
}, 1000);
$current.css('z-index', 0);
}, 1000); // END: setTimeout()
slides[3].css('z-index', -1) //<======= place here =========
}, 4000); // END: setInterval()
} // END: slideshow()
slideshow();
#charset "UTF-8";
/* CSS Document */
body {
margin: 0;
padding: 0;
}
#main-container {
height: 60vh;
width: 100vw;
overflow: hidden;
}
#slide-container {
width: 200vw;
height: 100%;
position: relative;
}
.slide {
background-position: center;
background-size: cover;
width: 50%;
height: 100%;
position: absolute;
transform: translate3d(100%,0,0);
z-index: 1;
transition: 1s cubic-bezier(.48,.14,.31,.97);
color: white;
line-height: 60vh;
text-align: center;
font-size: 70px;
}
#slide-1 {
background-image: url(https://media.mnn.com/assets/images/2015/03/forest-path-germany.jpg.653x0_q80_crop-smart.jpg);
transform: translate3d(0,0,0);
z-index: 0;
}
#slide-2 {
background-image: url(https://media.treehugger.com/assets/images/2016/03/woodland_trail.jpg.662x0_q70_crop-scale.jpg);
}
#slide-3 {
background-image: url(http://sim02.in.com/4fc598f2c9f2c0cdc5e0decc188d8d10_ft_xl.jpg);
}
#slide-4 {
background-image: url(https://media-cdn.tripadvisor.com/media/photo-s/05/fc/88/f9/waterloop-trail.jpg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main-container">
<div id="slide-container">
<div class="slide" id="slide-1">Slide 1</div>
<div class="slide" id="slide-2">Slide 2</div>
<div class="slide" id="slide-3">Slide 3</div>
<div class="slide" id="slide-4">Slide 4</div>
</div>
</div>

Play with classes instead, look how simple can be your code.
Use transitionend
You don't need to do crazy stuff nesting setTimeout uselessly - and you can have as many slides you want without changing a line of code:
var $slides = $('.slide'), // Cache them
tot = $slides.length, // How many slides?
c = 0, // Current Slide Counter
$next = $slides.eq(c).addClass("slideIn"); // Prepare first slide
function slideshow() {
$next.toggleClass("slideOut slideIn").on("transitionend", function() {
$(this).removeClass("slideOut");
});
$next = $slides.eq(++c % tot).addClass("slideIn");
}
setInterval(slideshow, 4000); // Use setInteval Here
#main-container {
height: 60vh;
overflow: hidden;
}
#slide-container {
height: inherit; /* P.S: why 200% width? :D */
position: relative;
}
.slide {
position: absolute;
left:0; top:0;
background: none 50% 50% / cover;
width: 100%;
height: inherit;
color: white;
line-height: 60vh;
text-align: center;
font-size: 70px;
transition: 1s cubic-bezier(.48, .14, .31, .97);
transform: translateX(100%);
}
.slideIn { /* CREATE A SLIDEIN CLASS */
transform: translateX(0);
z-index: 1; /* 1 is only needed at slideIn */
}
.slideOut { /* CREATE A SLIDEOUT CLASS */
transform: translateX(-30%);
z-index: 0; /* 0 is only needed on slideOut */
}
#slide-1 {background-image: url(//placehold.it/800x600/0fb);}
#slide-2 {background-image: url(//placehold.it/800x600/fb0);}
#slide-3 {background-image: url(//placehold.it/800x600/0bf);}
<div id="main-container">
<div id="slide-container">
<div class="slide" id="slide-1">Slide 1</div>
<div class="slide" id="slide-2">Slide 2</div>
<div class="slide" id="slide-3">Slide 3</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

Related

Why do I keep getting 4 slides when there are only 3 div elements?

I created a slideshow with 3 slides but for some reason, it keeps adding an additional slide
const slideshow = document.getElementById("slideshow");
const slides = slideshow.children;
let currentSlide = 0;
function goToSlide(n) {
slides[currentSlide].classList.remove("active");
currentSlide = (n + slides.length) % slides.length;
slides[currentSlide].classList.add("active");
updateSlideshowCounter();
}
function nextSlide() {
goToSlide(currentSlide + 1);
}
function prevSlide() {
goToSlide(currentSlide - 1);
}
function updateSlideshowCounter() {
const slideshowCounter = document.getElementById("slideshow-counter");
slideshowCounter.textContent = `${currentSlide + 1} / ${slides.length}`;
}
const prevButton = document.getElementById("prev-button");
prevButton.addEventListener("click", prevSlide);
const nextButton = document.getElementById("next-button");
nextButton.addEventListener("click", nextSlide);
updateSlideshowCounter();
#slideshow {
position: relative;
text-align: center;
width: 400px;
height: 300px;
border: 1px black solid;
}
.slide {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 1s;
}
.slide.active {
opacity: 1;
}
#slideshow-controls {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
align-items: center;
}
#prev-button,
#next-button {
padding: 10px 20px;
border: none;
background-color: #333;
color: #fff;
cursor: pointer;
}
#prev-button {
margin-right: 20px;
}
#next-button {
margin-left: 20px;
}
#slideshow-counter {
margin: 0 20px;
}
<div id="slideshow">
<div class="slide">Slide 1</div>
<div class="slide">Slide 2</div>
<div class="slide">Slide 3</div>
<div id="slideshow-controls">
<button id="prev-button">Prev</button>
<span id="slideshow-counter"></span>
<button id="next-button">Next</button>
</div>
</div>
Can someone tell me what my mistake is and how I can get 3 slides in the output instead of 4.
You're defining your slides with the statement const slides = slideshow.children;. Your slideshow has a total of 4 direct children, so the counter is technically correct (see slide 1, slide 2, slide 3, and slideshow-controls).
One approach to get just the slides you want is to use const slides = document.getElementsByClassName("slide"). I hope this helps!
The problem is your slides variable is not assigned to the correct list of elements, as the previous answer said, you should replace slideshow.children with either document.getElementsByClassName('slide') or document.querySelectorAll('.slide'), use any of the two.
By using slideshow.children, you're not getting .slide classes, you're getting all children of #slideshow.
So, your variable in line 67, should be as the following:
const slides = document.querySelectorAll('.slide');
or
const slides = document.getElementsByClassName('.slide');
You should keep slideshow controls out of your slideshow div. I am attaching Code Below. Run it and check.
const slideshow = document.getElementById("slideshow");
const slides = slideshow.children;
let currentSlide = 0;
function goToSlide(n) {
slides[currentSlide].classList.remove("active");
currentSlide = (n + slides.length) % slides.length;
slides[currentSlide].classList.add("active");
updateSlideshowCounter();
}
function nextSlide() {
goToSlide(currentSlide + 1);
}
function prevSlide() {
goToSlide(currentSlide - 1);
}
function updateSlideshowCounter() {
const slideshowCounter = document.getElementById("slideshow-counter");
slideshowCounter.textContent = `${currentSlide + 1} / ${slides.length}`;
}
const prevButton = document.getElementById("prev-button");
prevButton.addEventListener("click", prevSlide);
const nextButton = document.getElementById("next-button");
nextButton.addEventListener("click", nextSlide);
updateSlideshowCounter();
#slideshowbox {
position: relative;
width: 400px;
height: 300px;
}
#slideshow {
position: relative;
text-align: center;
width: 400px;
height: 300px;
border: 1px black solid;
}
.slide {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 1s;
}
.slide.active {
opacity: 1;
}
#slideshow-controls {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
align-items: center;
}
#prev-button,
#next-button {
padding: 10px 20px;
border: none;
background-color: #333;
color: #fff;
cursor: pointer;
}
#prev-button {
margin-right: 20px;
}
#next-button {
margin-left: 20px;
}
#slideshow-counter {
margin: 0 20px;
}
<div id="slideshowbox">
<div id="slideshow">
<div class="slide">Slide 1</div>
<div class="slide">Slide 2</div>
<div class="slide">Slide 3</div>
</div>
<div id="slideshow-controls">
<button id="prev-button">Prev</button>
<span id="slideshow-counter"></span>
<button id="next-button">Next</button>
</div>
</div>
Your slideshow div childs is throwing 4 because your 4th div is slideshow-controls. You may want to add -1 to the counter or redifine the way you make your div. Best of luck!

How to create an image that repeats for a js fade in and out background slideshow?

I am currently building a website and I want a aesthetically pleasing landing page with a background fade in and out slideshow comprised of pictures that repeat y and x. I have the fading slideshow working perfectly and all I need is to repeat the image across the screen. Adding background: repeat to the CSS does not work. Below is may code:
HTML:
<div class="mybody" id="slider">
<div>
<h2>Dog Adoption</h2>
<p>Find the perfect match for your new four legged companion</p>
</div>
</div>
JavaScript:
var curIndex = 0,
imgDuration = 3000,
slider = document.getElementById("slider"),
slides = slider.childNodes; //get a hook on all child elements, this is live so anything we add will get listed
imgArray = [
'../../static/main/images/slideshow/dog2.jpg',
'../../static/main/images/slideshow/dog3.jpg',
'../../static/main/images/slideshow/dog4.jpg',
'../../static/main/images/slideshow/dog1.jpg',
];
//
// Dynamically add each image frame into the dom;
//
function buildSlideShow(arr) {
for (i = 0; i < arr.length; i++) {
var img = document.createElement('img');
img.src = arr[i];
slider.appendChild(img);
}
// note the slides reference will now contain the images so we can access them
}
//
// Our slideshow function, we can call this and it flips the image instantly, once it is
called it will roll
// our images at given interval [imgDuration];
//
function slideShow() {
function fadeIn(e) {
e.className = "fadeIn";
};
function fadeOut(e) {
e.className = "";
};
fadeOut(slides[curIndex]);
curIndex++;
if (curIndex === slides.length) {
curIndex = 0;
}
fadeIn(slides[curIndex]);
setTimeout(function () {
slideShow();
}, imgDuration);
};
buildSlideShow(imgArray);
slideShow();
CSS:
.mybody{
width: 100%;
min-height: 100vh;
max-height: fit-content;
top: 0px;
left: 0px;
padding: 0px;
/*background: url(../images/slideshow/dog1.jpg);*/
display: flex;
justify-content: center;
align-items: center;
text-align: center;
margin: 0px;
position: relative;
background-repeat: repeat;
}
.mybody img {
transition: opacity 1.5s;
position: absolute;
left: 0;
top: 0;
opacity:0;
background-repeat: repeat;
}
.mybody img.fadeIn {
opacity:1;
}
When I just set the background image as a fixed image (no JS) I get the desired result:
However when I comment out the backgorund image (as in above code) and just have the JS slideshow as the background, this is the result:
I essentially just need this image from the second picture to repeat as in the first picture and cannot figure out how to make this happen although I am sure there is a simple fix/solution. If anyone could be of help it would be much appreciated. Thanks in advance!
You can't repeat an image without duplicating it. But you can repeat background so, you can make the slide using divs with background. Note the usage of css classes instead of jquery fade.
slide = 1;
setInterval(function() {
$(".slide").removeClass("active");
$(".div" + slide).addClass("active");
slide++
if (slide == 4) {
slide = 1;
}
}, 1000)
body {
height: 100vh;
width: 100%;
position: relative;
padding: 0;
margin: 0;
text-align: center;
padding: 30px;
}
.slide {
background-repeat: repeat;
background-size: 100px;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
opacity: 0;
transition: 1000ms all;
}
.slide.active {
opacity: 1;
}
.div1 {
background: url('https://picsum.photos/id/101/200');
}
.div2 {
background: url('https://picsum.photos/id/102/200');
}
.div3 {
background: url('https://picsum.photos/id/103/200');
}
.text {
position: relative;
z-index: 2;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<body>
<div class="slide div1">
</div>
<div class="slide div2">
</div>
<div class="slide div3">
</div>
<div class="text">
<h1>dog trainer</h1>
<p>best in the world</p>
</div>
</body>

jQuery slideshow with url's in variable fade between images

I have created a jQuery based slideshow that lives within a DIV on my webpage. The only problem is the images have no transition effect between each other, just one to the next without the first one slowly fading out and the next fading on.
I would like to crossfade these images. What am I missing in my JS?
var urls = ['https://example.com/front.png',
'https://example.com/interior-scaled.jpeg'];
var count = 1;
$('.hero').css('background-image', 'url("' + urls[0] + '")');
setInterval(function() {
$('.hero').css('background-image', 'url("' + urls[count] + '")');
count == urls.length-1 ? count = 0 : count++;
}, 6000);
});
LINK TO FIDDLE
If you are not opposed to using a jQuery slideshow library then may I suggest using Ken Wheelers Slick carousel jQuery lib.
slick.min.css minified size 1.4 KB
slick-theme.min.css minified size 3.07 KB (only use if you want slicks base theme styles)
slick.min.js minified size 51.9 KB
In your first comment you mentioned...
even if images slide like a carousel would be sufficient.
Well Slick makes easy work of both, plus loads of other cool options, event callbacks and responsive breakpoint settings. It might speed up creating sliding/fading carousels for your project utilising jQuery which you are already using.
I've include 2 hero slideshows in example below, both in fade: false mode.
#Hero_1 slideshow runs before images may have or have not loaded.
#Hero_2 uses $(window).on('load') to make sure your images have loaded before slideshow runs
// our hero examples as constant variables
const hero_1 = $('#hero_1');
const hero_2 = $('#hero_2');
// our slide image urls in constant variable array
const slides = [
'https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-patient-exam-room.jpeg',
'https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-interior-scaled.jpeg',
'https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-front.png'
];
// for each of the slide images as key > url
$.each(slides, function(key, url) {
// append slide to hero carousel div
$('.carousel', '.hero').append('<div class="slide" style="background-image:url(\'' + url + '\');"></div>');
});
// the below slick js should not run until the above each function has finished appending images in slides array
// slick hero carousel on init
$('.carousel', hero_1).on('init', function(slick) {
// add show class to hero div to animate height when slick init
$(hero_1).addClass('show');
// slick carousel options
}).slick({
slidesToShow: 1,
slidesToScroll: 1,
dots: false,
arrows: false,
fade: true,
adaptiveHeight: false,
autoplay: true,
infinite: true,
pauseOnFocus: false,
pauseOnHover: false,
autoplaySpeed: 4000,
speed: 1000,
draggable: false
});
// use this if you want all background images to load first
// tho may be slow to run depending on how many images and the image size you are loading
$(window).on('load', function() {
// slick on init
$('.carousel', hero_2).on('init', function(slick) {
// add show class to hero div to expand height
$(hero_2).addClass('show');
// slick options
}).slick({
slidesToShow: 1,
slidesToScroll: 1,
dots: false,
arrows: false,
fade: true,
adaptiveHeight: false,
autoplay: true,
infinite: true,
pauseOnFocus: false,
pauseOnHover: false,
autoplaySpeed: 4000,
speed: 1000,
draggable: false
});
});
.hero {
position: relative;
overflow: hidden;
background: rgba(0, 0, 0, .75);
min-height: 0;
height: 0;
transition: all 0.5s ease;
margin: 0 0 .5rem 0;
}
.hero.show {
min-height: 150px;
height: 150px;
/*
height:45%;
height:45vh;
min-height:400px;
*/
}
.hero .carousel {
position: absolute;
top: 0;
right: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 0.5s ease;
}
.hero .carousel.slick-initialized {
opacity: 1;
}
.hero .carousel .slick-list,
.hero .carousel .slick-track {
height: 100% !important;
}
.hero .carousel .slide {
background-color: none;
background-repeat: no-repeat;
background-size: cover;
background-position: 50% 50%;
height: 100%;
}
.hero .overlay {
color: #fff;
position: relative;
text-align: center;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-shadow: 1px 1px 2px rgba(0, 0, 0, .75);
}
/* for demo styling purposes */
BODY {
font-family: helvetica;
}
H1 {
font-size: 2rem;
font-weight: 600;
margin: 0 0 .5rem 0;
}
P {
margin: 0 0 .5rem 0;
}
.lead {
font-size: 1.4rem;
margin: 0 0 .5rem 0;
}
.row {
margin: 0 -4px 0 -4px;
}
.col {
float: left;
width: calc(50% - 8px);
padding: 0 4px 0 4px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css" rel="stylesheet" />
<div class="row">
<div class="col">
<p>
<code><strong>#hero_1</strong><br/></code>
<code><small>Slick inits after each function is complete.</small></code>
</p>
<div id="hero_1" class="hero">
<div class="carousel"></div>
<div class="overlay">
<h1>Hero 1</h1>
<p class="lead">
Tooth Hurty
</p>
</div>
</div>
</div>
<div class="col">
<p>
<code><strong>#hero_2</strong></code><br/>
<code><small>Waits for all imgs to load before init slick.</small></code>
</p>
<div id="hero_2" class="hero">
<div class="carousel"></div>
<div class="overlay">
<h1>Hero 2</h1>
<p class="lead">
Tooth Hurty
</p>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js"></script>
Here is the same code above but in fade: false mode...
#Hero_1 slideshow runs before images may have or have not loaded.
#Hero_2 uses $(window).on('load') to make sure your images have loaded before slideshow runs
// our hero examples as constant variables
const hero_1 = $('#hero_1');
const hero_2 = $('#hero_2');
// our slide image urls in constant variable array
const slides = [
'https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-patient-exam-room.jpeg',
'https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-interior-scaled.jpeg',
'https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-front.png'
];
// for each of the slide images as key > url
$.each(slides, function(key, url) {
// append slide to hero carousel div
$('.carousel', '.hero').append('<div class="slide" style="background-image:url(\'' + url + '\');"></div>');
});
// the below slick js should not run until the above each function has finished appending images in slides array
// slick hero carousel on init
$('.carousel', hero_1).on('init', function(slick) {
// add show class to hero div to animate height when slick init
$(hero_1).addClass('show');
// slick carousel options
}).slick({
slidesToShow: 1,
slidesToScroll: 1,
dots: false,
arrows: false,
fade: false,
adaptiveHeight: false,
autoplay: true,
infinite: true,
pauseOnFocus: false,
pauseOnHover: false,
autoplaySpeed: 4000,
speed: 1000,
draggable: false
});
// use this if you want all background images to load first
// tho may be slow to run depending on how many images and the image size you are loading
$(window).on('load', function() {
// slick on init
$('.carousel', hero_2).on('init', function(slick) {
// add show class to hero div to expand height
$(hero_2).addClass('show');
// slick options
}).slick({
slidesToShow: 1,
slidesToScroll: 1,
dots: false,
arrows: false,
fade: false,
adaptiveHeight: false,
autoplay: true,
infinite: true,
pauseOnFocus: false,
pauseOnHover: false,
autoplaySpeed: 4000,
speed: 1000,
draggable: false
});
});
.hero {
position: relative;
overflow: hidden;
background: rgba(0, 0, 0, .75);
min-height: 0;
height: 0;
transition: all 0.5s ease;
margin: 0 0 .5rem 0;
}
.hero.show {
min-height: 150px;
height: 150px;
/*
height:45%;
height:45vh;
min-height:400px;
*/
}
.hero .carousel {
position: absolute;
top: 0;
right: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 0.5s ease;
}
.hero .carousel.slick-initialized {
opacity: 1;
}
.hero .carousel .slick-list,
.hero .carousel .slick-track {
height: 100% !important;
}
.hero .carousel .slide {
background-color: none;
background-repeat: no-repeat;
background-size: cover;
background-position: 50% 50%;
height: 100%;
}
.hero .overlay {
color: #fff;
position: relative;
text-align: center;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-shadow: 1px 1px 2px rgba(0, 0, 0, .75);
}
/* for demo styling purposes */
BODY {
font-family: helvetica;
}
H1 {
font-size: 2rem;
font-weight: 600;
margin: 0 0 .5rem 0;
}
P {
margin: 0 0 .5rem 0;
}
.lead {
font-size: 1.4rem;
margin: 0 0 .5rem 0;
}
.row {
margin: 0 -4px 0 -4px;
}
.col {
float: left;
width: calc(50% - 8px);
padding: 0 4px 0 4px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css" rel="stylesheet" />
<div class="row">
<div class="col">
<p>
<code><strong>#hero_1</strong><br/></code>
<code><small>Slick inits after each function is complete.</small></code>
</p>
<div id="hero_1" class="hero">
<div class="carousel"></div>
<div class="overlay">
<h1>Hero 1</h1>
<p class="lead">
Tooth Hurty
</p>
</div>
</div>
</div>
<div class="col">
<p>
<code><strong>#hero_2</strong></code><br/>
<code><small>Waits for all imgs to load before init slick.</small></code>
</p>
<div id="hero_2" class="hero">
<div class="carousel"></div>
<div class="overlay">
<h1>Hero 2</h1>
<p class="lead">
Tooth Hurty
</p>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js"></script>
You can use transition: background-image. It might not be supported in all browsers, but most modern browsers should be fine.
Add
-webkit-transition: background-image 0.5s ease-in-out;
transition: background-image 0.5s ease-in-out;
to the css of the div which has the background image.
Here's a forked fiddle with a working example: https://jsfiddle.net/bmh2qu0e/1/
You can use transition on opacity and toggle opacity on background change, something like:
$(document).ready(function() {
var urls = ['https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-patient-exam-room.jpeg',
'https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-interior-scaled.jpeg',
'https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-front.png'
];
var count = 1;
var $hero = $('.hero');
$hero.css('background-image', 'url("' + urls[0] + '")');
setInterval(function() {
setTimeout(function() {
$hero.toggleClass('transparent');
setTimeout(function() {
$hero.css('background-image', 'url("' + urls[count] + '")');
count == urls.length - 1 ? count = 0 : count++;
$hero.toggleClass('transparent');
}, 300);
}, 300);
}, 6000);
});
.transparent {
opacity: 0;
}
.hero {
height: 45%;
height: 45vh;
min-height: 400px;
background-color: none;
text-align: center;
background-repeat: no-repeat;
background-size: cover;
background-position: 50% 50%;
-webkit-transition: opacity 0.5s ease-in-out;
transition: opacity 0.5s ease-in-out;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="hero"></div>
If you want to take a step further, you can make it more generic with class:
class ImageSlider {
imagePos = 0;
intevalHandle = null;
intervalMS = 6000;
constructor(elem, images, startImmediately) {
this.images = images || [];
this.elem = $(elem);
if (startImmediately) {
this.startSlider();
}
}
startSlider() {
if (this.startTimer()) {
this.imagePos = 0;
this.onTimerInterval();
}
};
pauseSlider() {
this.clearTimer();
}
resumeSlider() {
this.startTimer();
}
stopSlider() {
this.clearTimer();
this.imagePos = 0;
};
startTimer() {
if (this.intervalHandle != null) {
return false;
}
this.intervalHandle = setInterval(() => this.onTimerInterval(), this.intervalMS);
return true;
};
clearTimer() {
if (this.intervalHandle) {
this.clearInterval(this.intervalHandle);
this.intervalHandle = null;
}
}
onTimerInterval() {
if (this.images.length <= 0) {
return;
}
setTimeout(() => {
this.elem.toggleClass('transparent');
setTimeout(() => {
if (this.imagePos >= this.images.length) {
this.imagePos = 0;
}
this.elem.css('background-image', 'url("' + this.images[this.imagePos] + '")');
this.imagePos++;
this.elem.toggleClass('transparent');
}, 300);
}, 300);
}
}
$(document).ready(function() {
var urls = ['https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-patient-exam-room.jpeg',
'https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-interior-scaled.jpeg',
'https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-front.png'
];
var slider1 = new ImageSlider('#ss1', urls, true);
var slider2 = new ImageSlider('#ss2', [...urls].reverse(), true);
});
.transparent {
opacity: 0;
}
.hero {
height: 45%;
height: 45vh;
min-height: 400px;
background-color: none;
text-align: center;
background-repeat: no-repeat;
background-size: cover;
background-position: 50% 50%;
-webkit-transition: opacity 0.5s ease-in-out;
transition: opacity 0.5s ease-in-out;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="ss1" class="hero"></div>
<div id="ss2" class="hero"></div>
You can't cross-fade a single background image using CSS.
A possible solution is to have two containers inside the hero <div> you have there.
E.g:
<div class="hero">
<div class="img-container" id="first"></div>
<div class="img-container" id="second"></div>
</div>
For your desired effect of the crossfade you will need these images to cover the desired area on top of the hero <div>.
This can be done by these CSS rules:
.img-container {
background-repeat: no-repeat;
background-size: cover;
background-position: 50% 50%;
background-color: transparent;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
Now we need to have the images load in and cross-fade over one another.
$(document).ready(function() {
var urls = [
'imgURL1',
'imgURL2',
'imgURL3'
];
// Preload the images
var tempImg = []
for (var i = 0; i < urls.length; i++) {
(new Image()).src = urls[i]
}
// The currently shown image's index
var currentShown = 0;
// Get the containers
var first = $("#first");
var second = $("#second");
// This shows whether the second object is on top or not
var secondOnTop = true;
// Set the first container's value so that there is something on the screen and load the second image on top.
first.css('background-image', 'url("' + urls[urls.length - 1] + '")');
second.css({
backgroundImage: 'url("' + urls[0] + '")',
opacity: 1
});
// Change the image every X seconds
setInterval(function() {
var animationSpeed = 1000; // In milliseconds
// Increment currently shown image index
currentShown === urls.length - 1 ? currentShown = 0 : currentShown++;
// Determine which object has visual priority
var primaryObj = first;
var auxObj = second;
if (secondOnTop) {
primaryObj = second;
auxObj = first;
}
secondOnTop = !secondOnTop;
// Show aux obj background
auxObj.css({backgroundImage: 'url("' + urls[currentShown] + '")'});
auxObj.animate({
opacity: 1
}, animationSpeed);
// Change shown object's background and set to 0
primaryObj.animate({
opacity: 0,
}, animationSpeed, function() {
// Change the primary's background to the next in queue
var nextImg = currentShown === urls.length - 1 ? 0 : currentShown + 1;
primaryObj.css('background-image', 'url("' + urls[nextImg] + '")');
});
}, 6000);
});
I have created a fork of your fiddle available here: https://jsfiddle.net/YeloPartyHat/uLfr389g/88/
Here is a solution: (I had to replace shortened url with full url otherwise SO wouldn't let me save the answer)
$(document).ready(function(){
var urls = ['https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-patient-exam-room.jpeg',
'https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-interior-scaled.jpeg',
'https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-front.png'];
var totalLayers = 2;
var layerIndex = 0;
var count = 0;
$('.layer-' + layerIndex)
.removeClass('layer')
.css('background-image', 'url("' + urls[count] + '")');
console.log({first: layerIndex, second: (layerIndex + 1) % totalLayers, count})
setInterval(function() {
var outLayer = layerIndex
var inLayer = ++layerIndex % totalLayers
layerIndex = inLayer
count = ++count % urls.length;
console.log({first: outLayer, second: inLayer, count})
$('.layer-' + outLayer)
.addClass('animateXFadeOut');
$('.layer-' + inLayer)
.removeClass('layer')
.css('background-image', 'url("' + urls[count] + '")')
.addClass('animateXFadeIn');
setTimeout(function() {
$('.layer-' + outLayer).css({backgroundImage: 'none', opacity: 1});
$('.layers').removeClass('animateXFadeIn animateXFadeOut');
}, 1000);
}, 6000);
});
.hero {
/* height: 45%;
height: 45vh;
min-height: 400px;
*/
background-color: none;
text-align: center;
background-repeat: no-repeat;
background-size: cover;
background-position: 50% 50%;
}
#keyframes xfadein {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
#keyframes xfadeout {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
.animateXFadeIn {
animation-name: xfadein;
animation-duration: 1s;
}
.animateXFadeOut {
animation-name: xfadeout;
animation-duration: 1s;
}
.layer-0, .layer-1 {
display: block;
position: absolute;
height: 45%;
height: 45vh;
min-height: 400px;
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="hero">
<div class="layers layer-0"></div>
<div class="layers layer-1"></div>
</div>
you can use one little class and one line of jquery to do that
$(document).ready(function(){
var urls = ['image_one_url',
'image_two_url',
'image_three_url'];
var count = 1;
$('.hero').css('background-image', 'url("' + urls[0] + '")');
$('.hero').addClass('animatedinout');
setInterval(function() {
$('.hero').css('background-image', 'url("' + urls[count] + '")');
count == urls.length-1 ? count = 0 : count++;
}, 6000);
});
.animatedinout{
animation: fadeinout;
animation-duration: 6000ms;
animation-timing-function: ease-in-out;
animation-iteration-count: infinite;
}
#keyframes fadeinout{
0%{
opacity: 0;
}
10%{
opacity: 1;
}
90%{
opacity: 1;
}
100%{
opacity: 0;
}
}
i just add a css class called animatedinout that use an animation forever for every 6000 mili seconds and add
$('.hero').addClass('animatedinout');
right before your setInterval.
I thank everyone for their hard work. The solution I found (because I was on a tight deadline) is actually pretty simple and combines JS and CSS to make for a "true" crossfade transition.
HTML:
<div id="background-images">
<div class="bgImages active" id="bgImg1"></div>
<div class="bgImages" id="bgImg2"><br></div>
<div class="bgImages" id="bgImg3"><br><br></div>
<div class="bgImages" id="bgImg4"><br></div>
<div class="bgImages" id="bgImg5"><br><br></div>
</div>
jQuery:
function cycleImages() {
var $active = $("#background-images .active");
var $next = $active.next().length > 0
? $active.next()
: $("#background-images div:first");
$next.css("z-index", 2); // move the next img up the stack
$active.fadeOut(1500, function() {
//fade out the top image
$active.css("z-index", 1).show().removeClass("active"); //reset z-index and unhide the image
$next.css("z-index", 3).addClass("active"); //make the next image the top one
});
}
$(document).ready(function() {
$("#cycler img").show();
// run every 6 seconds
setInterval(cycleImages, 6000);
});
CSS:
#background-images {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 670px;
z-index: -5;
}
#bgImg1, #bgImg2, #bgImg3, #bgImg4, #bgImg5 {
width: 100%;
height: 100%;
position: fixed;
background-position-x: center;
background-position-y: center;
background-size: cover;
background-repeat: no-repeat;
}
#bgImg1 { background-image: url("https://image1.jpg"); }
#bgImg2 { background-image: url("https://image2.png"); z-index: 2; }
#bgImg3 { background-image: url("https://image3.jpeg"); }
#bgImg4 { background-image: url("https://image4.jpg"); }
#bgImg5 { background-image: url("https://image5.jpeg"); }
It was a clever way of using z-index combined with active status to get the images to actually crossfade with no white "blink".
Found it on a CodePen here.

jQuery carousel slide animation

I am working on jQuery carousel. Here is my code:
// CAROUSEL
$('#left-arrow').click(previousSlide);
$('#right-arrow').click(nextSlide);
function nextSlide() {
var $currentSlide = $('#carousel .slide-image:first');
var width = $currentSlide.width();
var $lastSlide = $('#carousel .slide-image:last')
$currentSlide.animate({ 'margin-left': -width }, 1000, function() {
$currentSlide.remove().css({ 'margin-left': '0px' });
$lastSlide.after($currentSlide);
});
}
function previousSlide() {
var $currentSlide = $('#carousel .slide-image:first');
var width = $currentSlide.width();
var $last = $('#carousel .slide-image:last');
$last.remove().css({ 'margin-left': -width });
$currentSlide.before($last);
$last.animate({ 'margin-left': '0px' }, 1000);
}
/* CAROUSEL */
#slide1 {
background-color: red;
}
#slide2 {
background-color: blue;
}
#slide3 {
background-color: magenta;
}
#carousel {
overflow: hidden;
white-space: nowrap;
position: relative;
width: 100vw;
height: 75vh;
}
.slide-image {
width: 100vw;
height: 75vh;
background-position: center;
background-size: cover;
display: inline-block;
}
.arrow {
width: 2%;
position: absolute;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
}
#right-arrow {
right: 30px;
}
#left-arrow {
left: 30px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<section id="carousel">
<div class="arrow" id="left-arrow">L</div>
<div class="arrow" id="right-arrow">R</div>
<div class="slide-image" id="slide1">
</div>
<div class="slide-image" id="slide2">
</div>
<div class="slide-image" id="slide3">
</div>
</section>
The problem is that it is acting differently for left and right side. If you click left side multiple times, it will just move the slider number of times, according on the number of clicks at once. If you however click multiple times on the right side, it will always move only once. That is because the current slide is being pushed before the last slide and there is no slide yet. However I would like it to act the same as the left side so it should be able to move multiple times.
How could I achieve that behaviour?
Try stoping the current animation and move to next slide.
You can use a variable like nextAnimation to check if the animation is still playing.
// CAROUSEL
$('#left-arrow').click(previousSlide);
$('#right-arrow').click(nextSlide);
var nextAnimation = false;
function nextSlide() {
var $currentSlide = $('#carousel .slide-image:first');
var width = $currentSlide.width();
var $lastSlide = $('#carousel .slide-image:last');
if(nextAnimation) {
$currentSlide.stop();
$currentSlide.remove().css({ 'margin-left': '0px' });
$lastSlide.after($currentSlide);
$currentSlide = $('#carousel .slide-image:first');
width = $currentSlide.width();
$lastSlide = $('#carousel .slide-image:last');
}
nextAnimation = true;
$currentSlide.animate({ 'margin-left': -width }, 1000, function() {
$currentSlide.remove().css({ 'margin-left': '0px' });
$lastSlide.after($currentSlide);
nextAnimation = false;
});
}
function previousSlide() {
var $currentSlide = $('#carousel .slide-image:first');
var width = $currentSlide.width();
var $last = $('#carousel .slide-image:last');
$last.remove().css({ 'margin-left': -width });
$currentSlide.before($last);
$last.animate({ 'margin-left': '0px' }, 1000);
}
/* CAROUSEL */
#slide1 {
background-color: red;
}
#slide2 {
background-color: blue;
}
#slide3 {
background-color: magenta;
}
#carousel {
overflow: hidden;
white-space: nowrap;
position: relative;
width: 100vw;
height: 75vh;
}
.slide-image {
width: 100vw;
height: 75vh;
background-position: center;
background-size: cover;
display: inline-block;
}
.arrow {
width: 2%;
position: absolute;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
}
#right-arrow {
right: 30px;
}
#left-arrow {
left: 30px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<section id="carousel">
<div class="arrow" id="left-arrow">L</div>
<div class="arrow" id="right-arrow">R</div>
<div class="slide-image" id="slide1">1
</div>
<div class="slide-image" id="slide2">2
</div>
<div class="slide-image" id="slide3">3
</div>
</section>

How to rotate background image on scroll

I am trying to rotate background image while scrolling. The effect should look like cube. Sadly I could not find a way with css and jquery to make it look like in the video. On the gif, when scrolling down from gallery to next page, there is grill background which rotates and stretches by amount of page shown.
EDIT: Rotating animation has to look like this
What have I tried so far (unsuccessfully)
$(function() {
var rotation = 0,
scrollLoc = 0;
$(window).scroll(function() {
$("#galerie").text($(document).scrollTop() + "=ScrollTop,WinHeight=" + $(window).height());
var newLoc = $(document).scrollTop();
var diff = scrollLoc - newLoc;
rotation += diff, scrollLoc = newLoc;
var rotationStr = "rotateX(" + rotation / ($(window).height() * 2) + "turn)";
$("#home").css({
"-webkit-transform": rotationStr,
"-moz-transform": rotationStr,
"transform": rotationStr,
"background-size": -rotation
});
});
})
body,
html {
height: 100%;
}
body {
background-color: #090909;
}
#home {
height: 100%;
position: relative;
overflow: hidden;
}
#galerie {
color: green;
}
#home:before {
content: "";
background-repeat: no-repeat;
background-size: 100% auto;
background-position: center bottom;
background-color: grey;
background-attachment: initial;
position: absolute;
width: 100%;
height: 100%;
z-index: -1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id=box>
<div id="home">
TestText
</div>
</div>
<div id="galerie">
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>
<div id="gale">
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>
</body>
I've made the top part for you. And I'm sure you'll make the bottom one yourself (see the snippet in the Full page mode):
$(function() {
$(window).scroll(function() {
$('#home_bg').css({
'transform': 'rotateX(' + 30 * (1 + Math.PI * Math.atan($(document).scrollTop() / 300)) + 'deg)'
});
});
})
html,
body {
height: 100%; margin:0 ;padding:0
}
body {
background-color: #333;
}
#home {
height: 30vh;
position: relative;
overflow: hidden;
perspective: 300px;
color:#fff;
text-align:center;
}
#home_bg {
content: "";
background: repeating-linear-gradient(45deg, #555, #555 2px, transparent 0, transparent 60px), repeating-linear-gradient(-45deg, #555, #555 2px, transparent 0, transparent 60px) 30px 30px / 170px 170px;
position: absolute;
z-index: -1;
top: -100%;
left: -50%;
width: 200%;
height: 200%;
transform: rotateX(30deg);
transform-origin: 50% 100%;
}
#galerie {
color: green;
display: flex;
justify-content: center;
flex-flow: row wrap;
width: 50%;
margin: 0 auto 70vh;
}
#galerie img {
width: 45%;
margin: 0 auto 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="home">
<h1>Lorem ipsum?</h1>
<div id="home_bg"></div>
</div>
<div id="galerie">
<p></p>
<img src="https://picsum.photos/100/100?1">
<img src="https://picsum.photos/100/100?2">
<img src="https://picsum.photos/100/100?3">
<img src="https://picsum.photos/100/100?4">
<img src="https://picsum.photos/100/100?5">
<img src="https://picsum.photos/100/100?6">
</div>
</body>
Hope you want like this.
$(function() {
var rotation = 0;
var interval;
var gear = $('.gear');
function animate() {
gear.css('transform', 'rotate('+rotation+'deg)');
rotation += 10;
rotation %= 360;
}
function startAnim() {
if (!interval) {
interval = setInterval(animate, 50);
}
}
function stopAnim() {
clearInterval(interval);
interval = null;
}
$(document).scroll(startAnim).mouseup(stopAnim);
});
body{
height: 1000px;
}
.gear{
background: url("https://cdn.pixabay.com/photo/2016/01/03/11/24/gear-1119298_960_720.png") no-repeat;
width: 100%;
height: 100px;
position: fixed;
background-position: center center;
background-size: contain;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gear"></div>

Categories