I have built a really simple carousel but there is one issue. In my carousel i have three slides, a previous button and a next button. What I want is when I click the next button and is on the last slide to go to the first slide. Moreover, when i click the previous button and is on the first slide to go to the last slide. How can i achieve it?
Thanks
//Main Container
var carouseContainer = document.querySelector("#carousel-container");
//Carousel Container
var carousel = document.querySelector("#carousel");
//Carousel Children
var carouselChildren = document.querySelector("#carousel").children;
//Carousel Slides
var carouselOne = document.querySelector("#carousel-one")
var carouseTwo = document.querySelector("#carousel-two")
var carouselThree = document.querySelector("#carousel-three")
//Buttons
var buttonPrev = document.querySelector("#button-left");
var buttonNext = document.querySelector("#button-right");
buttonNext.addEventListener("click", function(){
for ( i = 0; i < carouselChildren.length; i++) {
carouselChildren[i].style.transform +="translateX(-300px)";
carouselChildren[i].style.transition +="all 2s ease";
}
});
buttonPrev.addEventListener("click", function(){
for ( i = 0; i < carouselChildren.length; i++) {
carouselChildren[i].style.transform +="translateX(300px)";
carouselChildren[i].style.transition +="all 2s ease";
}
});
* {
margin:0px;
padding:0px;
box-sizing: border-box;
list-style: none;
text-decoration: none;
}
#carousel-container {
width:300px;
height:300px;
overflow: hidden;
margin: 0 auto;
border:1px solid black;
}
#carousel {
width:900px;
height:300px;
}
#carousel-one, #carousel-two,#carousel-three {
width:300px;
height:300px;
float:left;
}
#carousel-one {
background:red;
}
#carousel-two {
background:green;
}
#carousel-three {
background:blue;
}
#buttons {
text-align: center;
margin-top:20px;
}
button {
border:none;
color:#fff;
padding:10px 20px;
display: inline-block;
margin-right:20px;
cursor: pointer;
}
<div id="carousel-container">
<div id="carousel">
<div id="carousel-one">
<h1>Carousel One Main Heading</h1>
<h2>Carousel One Sub Heading</h2>
</div>
<div id="carousel-two"></div>
<div id="carousel-three"></div>
</div>
</div>
<div id="buttons">
<button id="button-left">Previous</button>
<button id="button-right">Next</button>
</div>
Here's a working example from your code:
//Main Container
var carouseContainer = document.querySelector("#carousel-container");
//Carousel Container
var carousel = document.querySelector("#carousel");
//Carousel Children
var carouselChildren = document.querySelector("#carousel").children;
//Carousel Slides
var carouselOne = document.querySelector("#carousel-one")
var carouseTwo = document.querySelector("#carousel-two")
var carouselThree = document.querySelector("#carousel-three")
//Buttons
var buttonPrev = document.querySelector("#button-left");
var buttonNext = document.querySelector("#button-right");
var current = 0,
total = 3;
function moveTo(count) {
var translate = 'translateX(' + (-300 * current) + 'px)';
for (i = 0; i < carouselChildren.length; i++) {
carouselChildren[i].style.transform = translate;
}
}
buttonNext.addEventListener("click", function() {
current++;
if (current > total - 1) {
current = 0;
}
moveTo(current);
});
buttonPrev.addEventListener("click", function() {
current--;
if (current < 0) {
current = total - 1;
}
moveTo(current);
});
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
list-style: none;
text-decoration: none;
}
#carousel-container {
width: 300px;
height: 300px;
overflow: hidden;
margin: 0 auto;
border: 1px solid black;
}
#carousel {
width: 900px;
height: 300px;
}
#carousel-one,
#carousel-two,
#carousel-three {
width: 300px;
height: 300px;
float: left;
transition: all 2s ease;
}
#carousel-one {
background: red;
}
#carousel-two {
background: green;
}
#carousel-three {
background: blue;
}
#buttons {
text-align: center;
margin-top: 20px;
}
button {
border: none;
color: #fff;
padding: 10px 20px;
display: inline-block;
margin-right: 20px;
cursor: pointer;
}
<div id="carousel-container">
<div id="carousel">
<div id="carousel-one" class="slide">
<h1>Carousel One Main Heading</h1>
<h2>Carousel One Sub Heading</h2>
</div>
<div id="carousel-two" class="slide"></div>
<div id="carousel-three" class="slide"></div>
</div>
</div>
<div id="buttons">
<button id="button-left">Previous</button>
<button id="button-right">Next</button>
</div>
This is an example, however, I think you can improve a lot your code :-) . Once I did a carousel and the magic was with the active class and the animation, I mean if you can apply the translate to the active class and identify the direction according to the prev or next button, you will achieve it.
//Main Container
var carouseContainer = document.querySelector("#carousel-container");
//Carousel Container
var carousel = document.querySelector("#carousel");
//Carousel Children
var carouselChildren = document.querySelector("#carousel").children;
//Carousel Slides
var carouselOne = document.querySelector("#carousel-one")
var carouseTwo = document.querySelector("#carousel-two")
var carouselThree = document.querySelector("#carousel-three")
//Buttons
var buttonPrev = document.querySelector("#button-left");
var buttonNext = document.querySelector("#button-right");
buttonNext.addEventListener("click", function(){
var activeSlide = 0,
translate = 'translateX(-300px)';
for ( i = 0; i < carouselChildren.length; i++) {
if (carouselChildren[i].className) {
activeSlide = i;
}
carouselChildren[i].style.transform += translate;
carouselChildren[i].style.transition +="all 2s ease";
}
// remove the active class for the current slide
carouselChildren[activeSlide].className = '';
if(activeSlide + 1 >= carouselChildren.length){
carouselChildren[0].className = 'active';
for ( i = 0; i < carouselChildren.length; i++) {
carouselChildren[i].style.transform = 'translateX(0px)';
}
} else{
carouselChildren[++activeSlide].className = 'active';
}
});
buttonPrev.addEventListener("click", function(){
console.log(carouselChildren.length);
for ( i = 0; i < carouselChildren.length; i++) {
carouselChildren[i].style.transform +="translateX(300px)";
carouselChildren[i].style.transition +="all 2s ease";
}
});
* {
margin:0px;
padding:0px;
box-sizing: border-box;
list-style: none;
text-decoration: none;
}
#carousel-container {
width:300px;
height:300px;
overflow: hidden;
margin: 0 auto;
border:1px solid black;
}
#carousel {
width:900px;
height:300px;
}
#carousel-one, #carousel-two,#carousel-three {
width:300px;
height:300px;
float:left;
}
#carousel-one {
background:red;
}
#carousel-two {
background:green;
}
#carousel-three {
background:blue;
}
#buttons {
text-align: center;
margin-top:20px;
}
button {
border:none;
color:#fff;
padding:10px 20px;
display: inline-block;
margin-right:20px;
cursor: pointer;
}
<div id="carousel-container">
<div id="carousel">
<div id="carousel-one" class="active">
<h1>Carousel One Main Heading</h1>
<h2>Carousel One Sub Heading</h2>
</div>
<div id="carousel-two"></div>
<div id="carousel-three"></div>
</div>
</div>
<div id="buttons">
<button id="button-left">Previous</button>
<button id="button-right">Next</button>
</div>
Use a variable to keep track of the current slide and change the transform property based on it. I have made the function for the next button and you can use the same concept for the previous button as well.
var currentSlide = 1; // is in first slide
buttonNext.addEventListener("click", function(){
if(currentSlide == 3){
currentSlide = 0;
}
for ( i = 0; i < carouselChildren.length; i++) {
carouselChildren[i].style.transform="translateX("+(currentSlide*-300)+"px)";
carouselChildren[i].style.transition ="all 2s ease"; // you don't need to do this as well if you define it in css file once
}
currentSlide++;
});
P.S. It's a bad practice to add transform property to existing css transform property like you did in your code as you are adding further calculations that needs to happen in order to animate (translate) the divs. Always replace them.
Related
I'm a new javascript, let me direct to the point. I have heard that we have to avoid global variables as much as we can, so, i learn to use closure for make sure that variables can not access to each other.
I have slideShow function which is on the top and toggleMenu function on the bottom, these functions are work fine in my webpage.
My problems is when i changed position of functions, slideShow function to the bottom and toggleMenu function to the top, my webpage it looks not fine, doesn't work properly
May be there is something that i don't know? or i did something wrong? if any one would give me some advices i would appreciate that, thank you.
Here is original code
var slideShow = (function () {
var slideImages = document.getElementsByClassName("slide");
var leftSide = document.getElementById("arrow-left");
var rightSide = document.getElementById("arrow-right");
var slideBullets = document.getElementsByClassName("bullets");
var current = 0;
function reset() {
for (let i = 0; i < slideImages.length; i++) {
slideImages[i].style.display = 'none';
slideBullets[i].classList.remove("clicked");
}
};
function showImages() {
for (let i = 0; i < slideImages.length; i++) {
slideImages[0].style.display = 'block';
slideBullets[current].classList.add("clicked");
}
};
function arrowSlide() {
leftSide.addEventListener("click", function () {
reset();
if (current === 0) {
current = slideImages.length;
}
slideImages[current - 1].style.display = 'block';
current--;
slideBullets[current].classList.add("clicked");
});
rightSide.addEventListener("click", function () {
reset();
if (current === slideImages.length - 1) {
current = - 1;
}
slideImages[current + 1].style.display = 'block';
current++;
slideBullets[current].classList.add("clicked");
});
};
function showBulletsImages() {
for (let i = 0; i < slideBullets.length; i++) {
slideBullets[i].addEventListener("click", function () {
reset();
slideImages[i].style.display = 'block';
slideBullets[i].classList.add("clicked");
current = i;
});
}
};
function autoSlide() {
setInterval(function () {
rightSide.click();
slideBullets[current].classList.add('clicked')
}, 2000);
};
return {
reset: reset(),
showImages: showImages(),
arrowSlide: arrowSlide(),
showBulletsImages: showBulletsImages(),
autoSlide: autoSlide()
};
})();
var toggleMenu = (function () {
var mainTopics = document.getElementById("maintopics");
mainTopics.addEventListener("click", function (e) {
e.preventDefault();
e.stopImmediatePropagation();
mainTopics.classList.toggle("show");
});
document.addEventListener("click", function (e) {
if (e.target.id !== 'arrow-right') {
mainTopics.classList.remove("show");
}
});
return {
toggleMenu: toggleMenu()
};
})();
body {
margin: 0;
}
li, a{
text-decoration: none;
list-style-type: none;
text-decoration-line: none;
color: black;
}
/*main-menu*/
#mainmenu {
position: relative;
}
#mainmenu ul {
margin: 0;
padding: 0;
}
#mainmenu li {
display: inline-block;
}
#mainmenu a {
display: block;
width: 100px;
padding: 10px;
border: 1px solid;
text-align: center;
}
/*sub-topics*/
#subtopics {
position: absolute;
display: none;
margin-top: 10px;
width: 100%;
left: 0;
}
#maintopics.show #subtopics {
display: block;
}
#subtopics ul {
margin: 0;
padding: 0;
}
#subtopics li {
display: block;
}
#subTopics a {
text-align: left;
}
/*columns*/
#column1, #column2, #column3 {
position: relative;
float: left;
left: 125px;
margin: 0px 5px 0px 0px;
}
/*hover underline*/
#mainmenu li:hover {
text-decoration: underline;
}
/*slideshow*/
#slideshow {
position: relative;
width: 100%;
height: 100%;
}
#slide1 {
background-image: url(https://preview.ibb.co/mV3TR7/1.jpg);
}
#slide2 {
background-image: url(https://preview.ibb.co/bSCBeS/2.jpg);
}
#slide3 {
background-image: url(https://preview.ibb.co/kgG9Yn/3.jpg);
}
.slide {
background-repeat: no-repeat;
background-position: center;
background-size: 800px 400px;
width: 800px;
height: 400px;
margin: auto;
margin-top: 40px;
}
.slide-contain {
position: absolute;
left: 50%;
bottom: 50%;
transform: translate3d(-50%,-50%,0);
text-align: center;
}
.slide-contain span {
color: white;
}
/*arrow*/
.arrow {
position: absolute;
cursor: pointer;
top: 200px;
width: 0;
height: 0;
border-style: solid;
}
.arrow:hover {
background-color: #e0dede;
transition: background-color 0.6s ease;
}
#arrow-left {
position: absolute;
border-width: 30px 40px 30px 0px;
border-color: transparent gray transparent transparent;
left: 0;
margin-left: 300px;
}
#arrow-right {
border-width: 30px 0px 30px 40px;
border-color: transparent transparent transparent gray;
right: 0;
margin-right: 300px;
}
/*bullets*/
#slidebullet {
position: relative;
top: -30px;
text-align: center;
}
.bullets {
display: inline-block;
background-color: gray;
width: 15px;
height: 15px;
border-radius: 10px;
cursor: pointer;
transition: background-color 0.6s ease;
}
.clicked {
background-color: #ff0000;
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" type="text/css" href="index.css" />
</head>
<body>
<header></header>
<nav>
<div id="mainmenu">
<ul>
<li>Logo</li>
<li>Home</li>
<li id="maintopics">Topics
<div id="subtopics">
<div id="column1" class="columns">
<ul>
<li>example1</li>
<li>example2</li>
</ul>
</div>
</div>
</li>
</ul>
</div>
</nav>
<div id="slideshow">
<div id="slide1" class="slide">
<div class="slide-contain">
<span>Image One</span>
</div>
</div>
<div id="slide2" class="slide">
<div class="slide-contain">
<span>Image Two</span>
</div>
</div>
<div id="slide3" class="slide">
<div class="slide-contain">
<span>Image Three</span>
</div>
</div>
<div id="slidebullet">
<div id="bullet1" class="bullets"></div>
<div id="bullet2" class="bullets"></div>
<div id="bullet3" class="bullets"></div>
</div>
<div id="arrow-left" class="arrow"></div>
<div id="arrow-right" class="arrow"></div>
</div>
<script src="jquery.js"></script>
<script src="index.js"></script>
<script>
</script>
</body>
</html>
Then i changed position of functions
var toggleMenu = (function () {
var mainTopics = document.getElementById("maintopics");
mainTopics.addEventListener("click", function (e) {
e.preventDefault();
e.stopImmediatePropagation();
mainTopics.classList.toggle("show");
});
document.addEventListener("click", function (e) {
if (e.target.id !== 'arrow-right') {
mainTopics.classList.remove("show");
}
});
return {
toggleMenu: toggleMenu()
};
})();
var slideShow = (function () {
var slideImages = document.getElementsByClassName("slide");
var leftSide = document.getElementById("arrow-left");
var rightSide = document.getElementById("arrow-right");
var slideBullets = document.getElementsByClassName("bullets");
var current = 0;
function reset() {
for (let i = 0; i < slideImages.length; i++) {
slideImages[i].style.display = 'none';
slideBullets[i].classList.remove("clicked");
}
};
function showImages() {
for (let i = 0; i < slideImages.length; i++) {
slideImages[0].style.display = 'block';
slideBullets[current].classList.add("clicked");
}
};
function arrowSlide() {
leftSide.addEventListener("click", function () {
reset();
if (current === 0) {
current = slideImages.length;
}
slideImages[current - 1].style.display = 'block';
current--;
slideBullets[current].classList.add("clicked");
});
rightSide.addEventListener("click", function () {
reset();
if (current === slideImages.length - 1) {
current = - 1;
}
slideImages[current + 1].style.display = 'block';
current++;
slideBullets[current].classList.add("clicked");
});
};
function showBulletsImages() {
for (let i = 0; i < slideBullets.length; i++) {
slideBullets[i].addEventListener("click", function () {
reset();
slideImages[i].style.display = 'block';
slideBullets[i].classList.add("clicked");
current = i;
});
}
};
function autoSlide() {
setInterval(function () {
rightSide.click();
slideBullets[current].classList.add('clicked')
}, 2000);
};
return {
reset: reset(),
showImages: showImages(),
arrowSlide: arrowSlide(),
showBulletsImages: showBulletsImages(),
autoSlide: autoSlide()
};
})();
The issue seems to be with this
return {
toggleMenu: toggleMenu()
};
inside the toggleMenu immediately invoking function . This IIFE does not have any toggleMenu function
Beside return like
return {
reset: reset(),
showImages: showImages(),
arrowSlide: arrowSlide(),
showBulletsImages: showBulletsImages(),
autoSlide: autoSlide()
};
is not appropriate ,replace it with the following
There is no reason tha slideShow has to IIFE
return {
reset: reset,
showImages: showImages,
arrowSlide: arrowSlide,
showBulletsImages: showBulletsImages,
autoSlide: autoSlide
};
Here is a working demo at stackblitz
I have a simple image slider, with pagination controls.
I have coded it to add and remove an "active" class on the pagination
buttons on click. I would also like them to have the active class when the corresponding slide is showing.
How can I modify my code to achieve this?
<div id="slideshow">
<ul id="slides">
<li class="slide showing">
<div class="slide-description">
<h1 class="slide-title">All-in-one EV charging solution.</h1>
<p> Easy to use. Connected with smart charging capabilities. Our charging stations can be used at home,
work or in public.</p>
</div>
</li>
<li class="slide">
<div class="slide-description">
<h1 class="slide-title">Charging at work- a case study.</h1>
<p>In this new series of charging case studies, we dive into into the reasons why EV-Box partners are taking the green route.</p>
</div>
</li>
<li class="slide"> <div class="slide-description">
<h1 class="slide-title">Finding the best solution for your charging routine.</h1>
<p>
This whitepaper highlights the key answers that will guide you to acharging solution that best serves your needs.
</p>
</div>
</li>
</ul>
<button class="controls" id="previous"></button>
<button class="controls" id="next"></button>
<div id="pagination"></div>
var slides = document.querySelectorAll('#slides .slide'); // get all the slides
var currentSlide = 0;
var slideInterval = setInterval(nextSlide, 6000);
function nextSlide() {
goToSlide(currentSlide + 1);
}
function previousSlide() {
goToSlide(currentSlide - 1);
}
function goToSlide(n) {
slides[currentSlide].className = 'slide';
currentSlide = (n + slides.length) % slides.length;
slides[currentSlide].className = 'slide showing';
}
//Previous and Next controls
var next = document.getElementById('next');
var previous = document.getElementById('previous');
next.onclick = function() {
nextSlide();
};
previous.onclick = function() {
previousSlide();
};
//Pagination controls
var p = document.getElementById('pagination');
var phtml = '';
for(var i = 0; i < slides.length; i++) {
phtml += '<button></button>'; // create the pagination buttons for each slide
}
p.innerHTML = phtml; //insert the html for the buttons
var pbuttons = p.querySelectorAll('button'); // grab all the buttons
var activeButton = null; // reference to active button
for(var i = 0; i < pbuttons.length; i++) {
pbuttons[i].onclick = (function(n) {
return function() {
if(activeButton)
activeButton.classList.remove('active'); // delete class from old active button
activeButton = this;// change ref, this is current button
activeButton.classList.add('active');// add class for new
goToSlide(n);
};
})(i);
}
#slider {
min-height: 400px;
position: relative;
#slides {
min-height: 400px;
padding: 0;
margin: 0;
list-style-type: none;
.slide {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
opacity: 0;
z-index: 1;
min-height: 400px;
box-sizing: border-box;
background: $black;
color: $white;
display: flex;
align-items: center;
-webkit-justify-content: flex-end;
justify-content: flex-end;
-webkit-transition: opacity 1s;
-moz-transition: opacity 1s;
transition: opacity 1s;
&.showing {
opacity: 1;
z-index: 2;
}
&:nth-of-type(1) {
#include backImage('../images/evbox1.jpg');
}
&:nth-of-type(2){
#include backImage('../images/evbox2.jpg');
}
&:nth-of-type(3) {
#include backImage('../images/evbox3.jpg');
}
}
.slide-description {
width: 500px;
.slide-title {
width: 90%;
font-family: 'Open Sans', sans-serif;
font-size: 44px;
text-shadow: 0 2px 3px rgba($black, .2);
line-height: 1.1em;
margin-bottom: 10px;
}
p {
margin-bottom: 15px;
width: 90%;
font-size: 20px;
font-family: 'Open Sans', sans-serif;
font-weight: 300;
text-shadow: 0 2px 3px rgba($black, .2);
}
.btn {
#include button($blue, $font-color, $shadow-color);
}
}
#include respond-to($mobile) {
#media only screen and (max-width: $mobile) {
.slide:nth-of-type(3) {
background-position: left 0;
}
.slide-description {
height: 100%;
width: 100%;
padding: 8em 5em;
position: static;
text-align: center;
.slide-title {
font-size: 30px;
width: 100%;
}
.btn {
padding: 8px 16px;
}
}
p {
display: none;
}
}
}
}
}
/*Previous and Next Controls*/
.controls {
position: absolute;
top: 42%;
z-index: 10;
background: url('http://www.ev-box.com/Evbox-EN/includes/themes/evbox/assets/images/sprites#2x.png') no-repeat;
height: 50px;
width: 30px;
background-size: 369px 240px;
outline: 0;
border: 0;
cursor: pointer;
}
#previous {
right: 10px;
background-position: -50px -121px;
}
#next {
left: 10px;
background-position: -16px -121px;
}
// Pagination
#pagination {
position: absolute;
bottom: 30px;
right: 50%;
z-index: 10;
button {
border-radius: 50%;
border: 1px solid $white;
background-color: $white;
opacity: .8;
width: 14px;
height: 14px;
min-height: 14px;
border-width: 0;
margin-right: 5px;
&.active {
width: 15px;
height: 15px;
min-height: 15px;
border: 1px solid $white;
background-color: $primary;
opacity: 1;
&:focus {
outline: 0;
}
}
}
}
I updated the javascript as shown below. Use this in your code pen. you can see the diffrence. If you click next and previous button the corresponding pagination will be highlighted by using this javascript
document.addEventListener("DOMContentLoaded", function() {
var slides = document.querySelectorAll('#slides .slide'); // get all the slides
const totalSlides = 2 // Total number of slides count
var currentSlide = 0; // current slide
var previousSlide = totalSlides;
// var slideInterval = setInterval(nextSlide, 1000);
function nextSlide() {
previousSlide = currentSlide
if(totalSlides > currentSlide){
currentSlide += 1
}
else currentSlide = 0
goToSlide();
}
function PreviousSlide() {
if(currentSlide == 0){
previousSlide = currentSlide
currentSlide = totalSlides
}
else{
previousSlide = currentSlide
currentSlide -=1
}
goToSlide();
}
function goToSlide() {
slides[previousSlide].className = 'slide';
slides[currentSlide].className = 'slide showing';
var currentSlideButton = "button"+currentSlide
var previousSlideButton = "button"+previousSlide
document.getElementById(currentSlideButton).classList.add('active');
document.getElementById(previousSlideButton).classList.remove('active');
}
//Previous and Next controls
var next = document.getElementById('next');
var previous = document.getElementById('previous');
next.onclick = function() {
PreviousSlide();
};
previous.onclick = function() {
nextSlide();
};
//Pagination controls
var p = document.getElementById('pagination');
var phtml = '';
for(var i = 0; i < slides.length; i++) {
phtml += '<button id=button'+i+'></button>'; // create the pagination buttons for each slide
}
p.innerHTML = phtml; //insert the html for the buttons
var pbuttons = p.querySelectorAll('button'); // grab all the buttons
var activeButton = null; // reference to active button
for(var i = 0; i < pbuttons.length; i++) {
pbuttons[i].onclick = (function(n) {
return function() {
if(activeButton)
activeButton.classList.remove('active'); // delete class from old active button
activeButton = this;// change ref, this is current button
activeButton.classList.add('active');// add class for new
goToSlide(n);
};
})(i);
}
goToSlide();// Initialising goToSlide method
});
I have been trying to use this fading slideshow code that I have found from this website.. http://blog.crondesign.com/2012/01/free-javascript-for-rotating-website.html
My main problem is that my divs will not stack on top of each other and I have researched of different ways like z-indexing and position:absolute and none of them seem to work. Can someone please have a look at my code to see what isn't working!
HTML:
<div id="slideshow_container">
<div id="banner2" class="banner"></div>
<div id="banner3" class="banner"></div>
<div id="banner4" class="banner"></div>
<div id="banner5" class="banner"></div>
<div id="banner1" class="banner"></div>
</div>
CSS
#slideshow_container
{
height:486px;
width: 806px;
margin-top: 0%;
margin:auto;
background-color:green;
display:block;
}
.banner
{
z-index:1;
height:486px;
width:806px;
top:0px;
background:#FFF;
border:solid 1px #CCC
position: absolute;
}
#banner1
{
background:green;
z-index: 5;
}
#banner2
{
background: blue;
z-index:6;
}
#banner3
{
background:#F90;
}
#banner4
{
background:#FFC;
}
#banner5
{
background:#99CCFF;
}
#slideshow_container
{
height:486px;
width: 806px;
margin-top: 0%;
margin:auto;
background-color:green;
display:block;
}
.banner
{
z-index:1;
height:486px;
width:806px;
top:0px;
background:#FFF;
border:solid 1px #CCC
position: absolute;
}
#banner1
{
background:green;
z-index: 5;
}
#banner2
{
background: blue;
z-index:6;
}
#banner3
{
background:#F90;
}
#banner4
{
background:#FFC;
}
#banner5
{
background:#99CCFF;
}
Javascript
var imageCount = 5; //how many images in total?
var changeSpeed = 3; //how many seconds between fades?
var fadeSpeed = 0.5; //how many seconds should the fade take?
var fps = 25; //animation frames per second
//BANNER FUNCTIONS:
var topImgID
var changeInterval
function $(id)
{
return(document.getElementById(id));
}
function changeOpac(obj, opacity)
{
obj = obj.style;
obj.opacity = (opacity / 100);
obj.MozOpacity = (opacity / 100);
obj.KhtmlOpacity = (opacity / 100);
obj.filter = "alpha(opacity=" + opacity + ")";
}
function changeImage()
{
var nextImgID = ( topImgID+1 <= imageCount ? topImgID+1 : 1 ); //get id number of next image in list
var nextImg = $('banner'+nextImgID);
var lastImg = $('banner'+topImgID);
var opac = 0;
changeOpac( nextImg, opac) //make next image invisible, then bring it to the top:
lastImg.style.zIndex = 2;
nextImg.style.zIndex = 3;
var fadeInterval = setInterval(function()
{
if(opac < 100)
{
opac += Math.ceil(100/(fadeSpeed*fps));
changeOpac(nextImg, opac);
}
else
{
lastImg.style.zIndex = 1;
clearInterval(fadeInterval);
}
}, 1000/fps);
topImgID = nextImgID;
}
function startBanner(firstImageID)
{
topImgID = (firstImageID==undefined ? 1+Math.floor(Math.random()*(imageCount)) : firstImageID);
$('banner'+topImgID).style.zIndex = 2;
changeInterval = setInterval(changeImage, changeSpeed*1000);
}
you forgot to close your border styles, so position:absolute isn't being read:
.banner
{
z-index:1;
height:486px;
width:806px;
top:0px;
background:#FFF;
border:solid 1px #CCC <----------- missing ';'
position: absolute;
}
Anyone know how can I set auto-scroll (with loop) in div with overflow:hidden; ?
Example
<div class="container" style="width:500px; max-width:500px; height:100px; max-height:100px; background:#F00; overflow:hidden;">
<div class="element_01" style="width:500px; height:100px; float:left;"></div>
<div class="element_02" style="width:500px; height:100px; float:left;"></div>
</div>
final effect?
Show element_01 -> wait 5 sec -> smooth scroll to element_02 -> wait 5 sec // and repeat
This example uses positioning instead of scrolling.
Scrolling with an overflow hidden element works, but can be buggy.
http://codepen.io/anon/pen/tqgyA
$(document).ready(function() {
var numSlides = $('ul.scroller').children().length,
counter = 0;
windowHeight = $('.window').height();
setInterval(function() {
counter++;
if (counter == numSlides) {
counter = 0;
$('.scroller').css('top', '0');
} else {
var toMove = (counter * windowHeight);
$('.scroller').css('top', '-'+toMove.toString()+'px');
}
}, 2000)
});
html { font-family: Helvetica, Arial }
.window {
width: 300px;
height: 200px;
overflow: hidden;
position: relative;
border: 2px solid skyblue;
}
ul.scroller {
width: 100%;
position: absolute;
top: 0;
left: 0;
list-style-type: none;
padding: 0;
margin: 0;
-webkit-transition: top .5s ease;
transition: top .5s ease;
}
ul.scroller li {
width: 100%;
height: 200px;
box-sizing: border-box;
padding: 80px 0;
text-align: center;
font-size: 28px;
}
ul.scroller li:nth-child(2n+2) { background: #F5F5F5 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="window">
<ul class="scroller">
<li>
First Item
</li>
<li>
Second Item
</li>
<li>
Third Item
</li>
<li>
Fourth Item
</li>
</ul>
</div>
You can use scrollTo jQuery plugin:
http://demos.flesler.com/jquery/scrollTo/
and repeat a function using setTimeout(function(){ $.scrollTo('#element'); }, 5000);
With core javascript:
<div class="container" style="width:500px; max-width:500px; height:100px; max-height:100px; background:#F00; overflow:hidden;">
<div class="element_01" style="width:500px; height:100px; float:left;">aaa</div>
<div class="element_02" style="width:500px; height:100px; float:left;">bbb</div>
</div>
<script>
var container=document.getElementsByClassName('container')[0];
var start = 0;
var smoothVal = 20;
var waitVal = 5000;
function smooth(){
var interval=setInterval(function(){
start++;
container.scrollTop = start;
if(start>100) {
clearInterval(interval);
wait();
}
},smoothVal)
}
function wait(){
start = 0;
container.scrollTop = start;
setTimeout(function(){
smooth();
},waitVal)
}
smooth();
</script>
I'm a newbie when it comes to jQuery and I'm fiddling around with a slider of sorts that loads images from a array and posts the result to a div. The way I have it set up it loads the image tag and image source and places it to an empty div. Now any animations in jQuery that I've seen what work in conjunction with an array have been formatted much differently. I should mention that I'm not looking for elegant, but just code that works.
Basically, is it possible to incorporate transitions with the way I'm doing it now? And if so, how? Nothing fancy, just a fade or swipe effect.
jsFiddle so far
var imgArray =
['<img src="http://placehold.it/400x300/cf5">',
'<img src="http://placehold.it/400x300/555">',
'<img src="http://placehold.it/400x300/f0f">',
'<img src="http://placehold.it/400x300/05b">']
counter = -1;
$('#nextimage').click(function () {
counter = (counter + 1) % imgArray.length;
console.log(imgArray[counter]);
document.getElementById("result1").innerHTML = (imgArray[counter]);
});
$('#previmage').click(function () {
counter = (counter - 1);
console.log(imgArray[counter]);
document.getElementById("result1").innerHTML = (imgArray[counter]);
});
html
<div class="container">
<div class="slider_wrapper">
<div id="slider">
<div class="img-wrap">
<div id="result1"></div>
</div>
</div>
</div>
</div>
<div id="footer">
<img title="Previous Image" alt="prev image" src="https://dl.dropboxusercontent.com/u/65639888/image/prev.png">
<img title="Next Image" alt="next image" src="https://dl.dropboxusercontent.com/u/65639888/image/next.png">
</div>
css
body {
background-color:black;
}
.container{
padding:5px;
border:1px dashed black;
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
box-sizing:border-box;
background: black;
}
.slider_wrapper{
overflow:hidden;
position:relative;
max-width:100%;
height:auto;
top:auto;
border-style: dashed;
border-color: white;
}
#slider{
position: relative;
list-style: none;
overflow: hidden;
margin:0px;
border-style: solid;
border-color: green;
}
#slider img{
width: 100%;
height:auto;
position: relative;
float: left;
}
.nvgt{
position:absolute;
top: 0px;
height: 100%;
width: 50%;
opacity: 0;
}
#footer {
position: fixed;
bottom: 0;
width: 100%;
background: BLACK;
line-height: 2;
text-align: center;
color: #FFFFFF;
font-size: 14px;
font-weight: bold;
text-shadow: 0 1px 0 #84BAFF;
box-shadow: 0 0 15px #FFFFFF;
opacity: 0.1;
padding:0;
margin:0;
}
#footer img {
padding-top:10px;
padding-bottom: 5px;
padding-right:20px;
padding-left:20px;
height: 30px;
}
#footer:hover {
opacity: 1;
}
ul, menu, dir, html, body {
-webkit-margin-end: 0px;
-webkit-padding-start: 0px;
margin:0px;
}
The trick is to wait until the image has been loaded.
var imgArray =
['<img src="http://placehold.it/400x300/cf5">',
'<img src="http://placehold.it/400x300/555">',
'<img src="http://placehold.it/400x300/f0f">',
'<img src="http://placehold.it/400x300/05b">']
counter = -1;
function imgTransition() {
$('#result1').fadeOut(300, function() {
$('#result1').html(imgArray[counter]);
$('#result1 > img').on('load', function() {
$('#result1').fadeIn(500);
});
});
};
$('#nextimage').click(function () {
counter = (counter + 1) % imgArray.length;
console.log(imgArray[counter]);
imgTransition();
});
$('#previmage').click(function () {
counter = (counter - 1);
console.log(imgArray[counter]);
imgTransition();
});
JSFiddle
see jsfiddle
var imgArray =
['<img src="http://placehold.it/400x300/cf5">',
'<img src="http://placehold.it/400x300/555">',
'<img src="http://placehold.it/400x300/f0f">',
'<img src="http://placehold.it/400x300/05b">'],
counter = -1;
var animate = false; //stopping invalid click during animation
function animatable() {
$('#result1').slideUp(300, function() {
$('#result1').html(imgArray[counter]);
$('#result1 > img').on('load', function() {
//$('#result1').fadeIn(500);
$( '#result1' ).animate({
height: "toggle"
}, 1000 , function(){
animate = false;
});
});
});
};
function next(){
if(!animate){
animate = true;
counter = (counter + 1) % imgArray.length;
console.log(counter);
$("#result1").fadeIn().html(imgArray[counter]);
animatable();
}
};
next();
$('#nextimage').click(next);
$('#previmage').click(function () {
if(!animate){
animate = true;
if(counter=='0'){
counter= imgArray.length;
}
counter = (counter - 1);
console.log(imgArray[counter]);
$("#result1").html(imgArray[counter]);
animatable();
}
});
update with animatable
Previous and next button working properly with fade out effect
var imgArray = ['<img src="http://placehold.it/400x300/cf5">',
'<img src="http://placehold.it/400x300/555">',
'<img src="http://placehold.it/400x300/f0f">',
'<img src="http://placehold.it/400x300/05b">']
counter = -1;
function imgTransition() {
$('#result1').fadeOut(300, function() {
$('#result1').html(imgArray[counter]);
$('#result1 > img').on('load', function() {
$('#result1').fadeIn(500);
});
});
};
function next() {
counter = (counter + 1) % imgArray.length;
console.log(counter);
imgTransition();
};
next();
$('#nextimage').click(next);
$('#previmage').click(function() {
if (counter == '0') {
counter = imgArray.length;
}
counter = (counter - 1);
console.log(imgArray[counter]);
imgTransition();
});
JSFIIDLE