How to make an automatic slideshow with buttons? - javascript

I created a automatic slideshow by using html , css and javascript but the next/previous and dot buttons are not working. When I made them work , slideshow becomes unautomatic. I added buttons to its cshtml file so nothing's missing. CSS file works perfectly as well. What is missing in my code ? Any help will be appreciated.
Javascript Code
let slideIndex = 0;
showSlides();
function showSlides() {
let i;
let slides = document.getElementsByClassName("mySlides");
let dots = document.getElementsByClassName("dot");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndex++;
if (slideIndex > slides.length) { slideIndex = 1 }
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex - 1].style.display = "block";
dots[slideIndex - 1].className += " active";
setTimeout(showSlides, 5000); // Change image every 2 seconds
}
var responsiveSlider = function () {
var slider = document.getElementById("slider");
var sliderWidth = slider.offsetWidth;
var slideList = document.getElementById("slideWrap");
var count = 1;
var items = slideList.querySelectorAll("li").length;
var prev = document.getElementById("prev");
var next = document.getElementById("next");
window.addEventListener('resize', function () {
sliderWidth = slider.offsetWidth;
});
var prevSlide = function () {
if (count > 1) {
count = count - 2;
slideList.style.left = "-" + count * sliderWidth + "px";
count++;
}
else if (count = 1) {
count = items - 1;
slideList.style.left = "-" + count * sliderWidth + "px";
count++;
}
};
var nextSlide = function () {
if (count < items) {
slideList.style.left = "-" + count * sliderWidth + "px";
count++;
}
else if (count = items) {
slideList.style.left = "0px";
count = 1;
}
};
next.addEventListener("click", function () {
nextSlide();
});
prev.addEventListener("click", function () {
prevSlide();
});
setInterval(function () {
nextSlide()
}, 5000);
};
window.onload = function () {
responsiveSlider();
}
#using SliderBannerProject.Model.Entity
#model List<Table_Slider>
#{
Layout = "~/Views/Shared/TestLayout.cshtml";
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="~/Content/mystyle.css" rel="stylesheet" />
<script defer src="~/Content/Script.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
</head>
<body>
<div class="slideshow-container">
<!-- Full-width images with number and caption text -->
#foreach (var item in Model)
{
<div class="mySlides w3-animate-fading">
<div class="numbertext">#item.ID</div>
<img src="#item.SliderPhoto" style="width:100%" />
<br />
<br />
<div class="text" id="text1" >#item.SliderInfo1</div>
<br />
<br />
<div class="text" id="update">
<p style="margin-bottom:-50px" >
<a href="/Test/UpdateInfo/#item.ID" id="update1">
Update Slider
</a>
</p>
</div>
</div>
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
}
</div>
<br>
</body>
<!-- The dots/circles -->
<br />
<div style="text-align:center">
#foreach (var item in Model)
{
<span class="dot" onclick="currentSlide(#item.ID)"></span>
}
</div>
<br />
<div style="text-align:center">
Add New Slider Photo
</div>
</html>
* {
box-sizing: border-box
}
.slideshow-container {
max-width: 1000px;
position: relative;
margin: auto;
animation: slide 10s infinite;
}
.mySlides {
display: none;
background-repeat: no-repeat;
background-size: cover;
width: 100%;
height: 80vh;
transition: all .2s ease-in-out;
animation: slide 10s infinite;
}
#text1 {
font-size: 100px;
font-display:swap;
font-style:oblique;
color:gray;
}
#update {
background-color: transparent;
border: none;
color: black;
padding: 16px 32px;
text-align: center;
font-size: 25px;
margin: 4px 2px;
opacity: 0.6;
transition: 0.3s;
display: inline-block;
text-decoration: none;
cursor: pointer;
}
#update1 {
color: black;
}
.prev, .next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
padding: 16px;
margin-top: -22px;
color: white;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
user-select: none;
}
/* Position the "next button" to the right */
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
/* On hover, add a black background color with a little bit see-through */
.prev:hover, .next:hover {
background-color: rgba(0,0,0,0.8);
}
.text {
color: #f2f2f2;
font-size: 15px;
padding: 8px 12px;
position: absolute;
bottom: 8px;
width: 100%;
text-align: center;
}
.numbertext {
color: #f2f2f2;
font-size: 12px;
padding: 8px 12px;
position: absolute;
top: 0;
}
.dot {
cursor: pointer;
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 5s ease;
}
.active, .dot:hover {
background-color: #717171;
}
.fade {
animation-name: fade;
animation-duration: 4s;
animation: slide 10s infinite;
}
#keyframes fade {
from {
opacity: 10
}
to {
opacity: 10
}
}

let slideIndex = 1;
let i;
let slides = document.getElementsByClassName("slides");
let dots = document.getElementsByClassName("dot");
auto();
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " active";
}
function auto() {
slideIndex++;
if (slideIndex > slides.length) {slideIndex = 1}
showSlides(slideIndex);
setTimeout(auto, 10000);
}
Try this i found that on youtube, here is the link.

Related

Adjust modal size to div shape

I'm working on my website and I'd like to create a slideshow. Hence, I have created the modal to expand the image after click - it works fine. However, I want to adjust the modal shape to the image size(thus the vertical photos look ugly in standard shape), but after many hours I gave up because I didn't find any satisfactory result.
HTML:
<div id="myModal" class="modal-wraper">
<span class="close cursor" onclick="closeModal()">×</span>
<div class="modal">
<div class="mySlides">
<div class="slide_1"></div>
</div>
<div class="mySlides">
<div class="slide_2"></div>
</div>
<div class="mySlides">
<div class="slide_3"></div>
</div>
</div>
CSS:
.modal-wraper {
position: fixed;
display: none;
top:0;
left: 0;
width: 100vw;
height: 100vh;
background-color: #000;
z-index: 1;
}
.modal {
position: absolute;
display: flex;
flex-direction: column;
height: 85vh;
width: 85vw;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border: solid 5px red;
}
.mySlides {
display: flex;
background-color: blue;
flex-basis: 100%;
}
.slide_1 {
width: 100%;
height: 100%;
background-image: url('../images/JF_3.jpg');
background-size:contain;
background-repeat: no-repeat;
object-fit: cover;
}
.slide_2 {
width: 100%;
height: 100%;
background-image: url('../images/JF_5.jpg');
background-size:cover;
}
JS
function openModal(n) {
document.getElementById("myModal").style.display = "block";
showSlides(n);
}
function closeModal() {
document.getElementById("myModal").style.display = "none";
}
var slideIndex = 0;
function changeSlides(n) {
showSlides(slideIndex += n);
}
function showSlides(n) {
var i;
var modal = document.getElementsByClassName('modal');
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("dot");
if (n < 0) {
slideIndex = slides.length-1;
} else if (n >= slides.length) {
slideIndex = 0
} else {
slideIndex = n;
}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex].style.display = "block";
dots[slideIndex].className += " active";
captionText.innerHTML = dots[slideIndex].alt;
}

My function for displayin the images in a carousel has an extra blank image

//get the object
let slideshowContainer = document.getElementById('slideshow-container');
//get the buttons
let next = document.querySelector('.next');
let prev = document.querySelector('.prev');
//create an index
var slideIndex = 0;
function showSlides(n) {
const slides = document.getElementsByClassName('product');
for (var i = 0; i < slides.length; i++) {
slides[i].style.display = 'none';
}
if (n < 0) {
slideIndex = slides.length
}
if (n > slides.length) {
slideIndex = 0
}
slides[slideIndex].style.display = 'block';
slideIndex = n;
}
function incrementSlides(n) {
showSlides(slideIndex += n)
}
//add event listeners
next.addEventListener('click', function () {
incrementSlides(1);
})
prev.addEventListener('click', function () {
incrementSlides(-1);
})
showSlides(slideIndex);
#section-one .categories {
height: 80px;
background: rgba(0, 0, 0, 0.9);
display: -webkit-box;
display: -ms-flexbox;
display: flex;
}
#section-one .categories li {
background: -webkit-gradient(linear, left top, right top, from(#0d0d0d), to(#202020));
background: linear-gradient(to right, #0d0d0d, #202020);
height: inherit;
width: 12.5%;
border-left: 1px solid black;
-webkit-transition: all ease-in 0.3s;
transition: all ease-in 0.3s;
}
#section-one .categories li:hover {
background: green;
}
#section-one .categories li a {
display: inline-block;
font-size: 0.95rem;
height: inherit;
width: 100%;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
}
#section-one .slideshow-container {
height: 1000px;
margin: auto;
position: relative;
background: grey;
}
#section-one .slideshow-container .prev,
#section-one .slideshow-container .next {
top: 50%;
background: blue;
font-size: 18px;
border-radius: 0 3px 3px 0;
width: auto;
position: absolute;
padding: 16px;
}
#section-one .slideshow-container .next {
right: 0;
border-radius: 3px 0 0 3px;
}
#section-one .slideshow-container .prev:hover,
#section-one .slideshow-container .next:hover {
background-color: rgba(0, 0, 0, 0.8);
}
<!-- Section-one -->
<section id="section-one">
<ul class="categories">
<li>HEADPHONES</li>
<li>EARPHONES</li>
<li>BLUETOOTH</li>
<li>WATERPROOF</li>
<li>SPORTS</li>
<li>METALLIC</li>
<li>WOODEN/BAMBOO</li>
<li>EARMUFF</li>
</ul>
<div id="slideshow-container">
<div class="product">
<p class="description"></p>
<div class="img">
<img
src="https://i.pinimg.com/originals/5a/e5/8f/5ae58f5036997cfd4636917403c3c951.jpg"
alt="image1"
style="width:100%"
/>
</div>
WIEW MORE
</div>
<div class="product">
<p class="description"></p>
<div class="img">
<img
src="https://images.unsplash.com/photo-1500382017468-9049fed747ef?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80"
alt="image2"
style="width:100%"
/>
</div>
WIEW MORE
</div>
<div class="product">
<p class="description"></p>
<div class="img">
<img
src="https://cdn.pixabay.com/photo/2017/02/22/20/02/landscape-2090495_960_720.jpg"
alt="image3"
style="width:100%"
/>
</div>
WIEW MORE
</div>
</div>
</section>
I'm trying to build a page with an image slider.
I watched some youtube videos, I combined the code and tried to make something to work but I came across an error. When I change for next or prev image I get a blank page and I don't know why.
I will create a code snippet to show you. I do not want just the problem to be solved but also the explanation, please!
Cheers!!!
You need to change your 2 " if " statements , since they dont consider the 0-based index on the array :
if (n < 0) {
slideIndex = slides.length - 1
}
if (n > slides.length - 1) {
slideIndex = 0
}
Here's the working jsFiddle with a few fix on your code:
https://jsfiddle.net/0mrpbv6c/
Basically,
I added some text to your a links to be able to click on them
PREV
NEXT
I fixed your 2 if conditions inshowSlides to continue the carousel as expected. Here you forgot the - 1, as your slides start from 0
if (n < 0) {
slideIndex = slides.length - 1;
}
if (n > slides.length - 1) {
slideIndex = 0;
}
I removed the following instruction, as you don't want to update slideIndex from n because it's already being updated when calling showSlides in incrementSlides, and also it overwrites the value you possibly got from the 2 if.
slideIndex = n;
I have tried fix your code.
function showSlides(n) {
console.log(n)
const slides = document.getElementsByClassName('product');
for (var i = 0; i < slides.length; i++) {
slides[i].style.display = 'none';
}
slideIndex = n; // edited
if (n < 0) {
slideIndex = slides.length
}
if (n >= slides.length) { // edited
slideIndex = 0
}
slides[slideIndex].style.display = 'block';
}

Add active class on pagination when corresponding slide is showing

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
});

Automatic and manual slideshow

I have to make a slideshow that has to work both automatic and manual.
For the manual part I have two buttons: next and previous that allows me to see the photos without having to wait a certain period of time between images.
When I don't click on the buttons, the slideshow goes automatic and the images change after six seconds (for example).
My problem is that, after I click on the previous/ next button, the images start to appear faster or they appear more than one on the screen.
Here is the code I am working with:
var slideIndex = 1;
showSlides(slideIndex);
function plusSlides(n) {
showSlides(slideIndex += n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("hidden");
if (n===undefined){n= ++slideIndex;}
if (n > slides.length) {slideIndex = 1;}
if (n < 1) {slideIndex = slides.length}
$(slides[slideIndex-1]).fadeIn(2000);
slides[slideIndex-1].style.display = "block";
$(slides[slideIndex-1]).delay(3000);
$(slides[slideIndex-1]).fadeOut(1000);
setTimeout(showSlides, 6000);
}
.hidden {
display: none;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<meta charset="utf-8">
<title>jQuery</title>
<link rel="stylesheet" href="lab5.css" media="screen" title="no title">
</head>
<body>
<h1 class="titlu">Goodies</h1>
<div align="center">
<button class="button" onclick="plusSlides(-1)" >Previous</button>
<button class="button" onclick="plusSlides(1)" >Next</button>
</div>
<div class="hidden">
<h4 class="num" > 1 / 5 </h4>
<img src="http://placehold.it/150x150?text=1">
</div>
<div class="hidden">
<h4 class="num"> 2 / 5 </h4>
<img src="http://placehold.it/150x150?text=2">
</div>
<div class="hidden">
<h4 class="num"> 3 / 5 </h4>
<img src="http://placehold.it/150x150?text=3">
</div>
<div class="hidden">
<h4 class="num"> 4 / 5 </h4>
<img src="http://placehold.it/150x150?text=4">
</div>
<div class="hidden">
<h4 class="num"> 5 / 5 </h4>
<img src="http://placehold.it/150x150?text=5">
</div>
</body>
</html>
Is there a way I can make the slideshow return to its "speed" of showing the images every six seconds after I click on previous/next?
Also, how can I prevent it from showing more than one image at a time?
Here's working code for an auto and manual slideshow with the timer as suggested by Scott.
It works with the html and css from this how to which the questioner based his code on.
https://www.w3schools.com/howto/howto_js_slideshow.asp
var slideIndex = 1;
var timer = null;
showSlides(slideIndex);
function plusSlides(n) {
clearTimeout(timer);
showSlides(slideIndex += n);
}
function currentSlide(n) {
clearTimeout(timer);
showSlides(slideIndex = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("dot");
if (n==undefined){n = ++slideIndex}
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " active";
timer = setTimeout(showSlides, 5000);
}
What's happening is that you are causing multiple timers to be started, which causes your callback function to run more often than it should.
You need to make sure that you capture the integer that is returned from your timer:
var timer = null; // Do this in a scope that is accessible to all your relevant functions
...then:
timer = setTimeout(showSlides, 6000);
So that you can cancel the timer where appropriate:
clearTimeout(timer);
You will want to clear your timer upon the clicking of the button, which will stop the automatic one from running and then you can start a new one, leaving you with only one running timer.
<!DOCTYPE html>
<html>
<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<style>
.mySlides {display:none;}
</style>
<body>
<h2 class="w3-center">Manual Slideshow</h2>
<div class="w3-content w3-display-container">
<img class="mySlides" src="img_snowtops.jpg" style="width:100%">
<img class="mySlides" src="img_lights.jpg" style="width:100%">
<img class="mySlides" src="img_mountains.jpg" style="width:100%">
<img class="mySlides" src="img_forest.jpg" style="width:100%">
<button class="w3-button w3-black w3-display-left" onclick="plusDivs(-1)">❮</button>
<button class="w3-button w3-black w3-display-right" onclick="plusDivs(1)">❯</button>
</div>
**SCRIPT CODES**
<script>
var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n) {
showDivs(slideIndex += n);
}
function showDivs(n) {
var i;
var x = document.getElementsByClassName("mySlides");
if (n > x.length) {slideIndex = 1}
if (n < 1) {slideIndex = x.length}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex-1].style.display = "block";
}
</script>
</body>
</html>
**//CSS CODES**
/* Slideshow container */
.slideshow-container {
height:500px;
position: relative;
margin: auto;
with:800px;
}
/* Hide the images by default */
.mySlides {
display: none;
}
/* Next & previous buttons */
.prev, .next {
background-color:gold;
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -22px;
padding: 20px;
color: black;
font-weight: bold;
font-size: 24px;
transition: 0.6s ease;
border-radius: 7 7px 7px 7;
}
/* Position the "next button" to the right */
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
/* On hover, add a black background color with a little bit see-through */
.prev:hover, .next:hover {
background-color: rgba(0,0,0,0.8);
color:white;
}
/* Caption text */
.text {
color:lime;
font-size: 22px;
padding: 8px 12px;
position: absolute;
bottom: 8px;
width: 100%;
text-align: center;
}
/* Number text (1/3 etc) */
.numbertext {
color:lime;
font-size: 22px;
padding: 8px 12px;
position: absolute;
top: 0;
}
/* The dots/bullets/indicators */
.dot {
cursor: pointer;
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #000000;
border-radius: 50%;
display: inline-block;
transition: background-color 0.2s ease;
}
.active, .dot:hover {
background-color: #ff0101;
}
/* Fading animation */
.fade {
-webkit-animation-name: fade;
-webkit-animation-duration: 0.2s;
animation-name: fade;
animation-duration: 6.5s;
}
#-webkit-keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
#keyframes fade {
from {opacity: .4}
to {opacity: 1}

Switching Between Two Slideshows with Javascript

I have a web page with a slideshow. The slideshow has three pictures. I would like to have a button on the page which enables users to switch between this slideshow and another with five different pictures. How would I program this button with JavaScript and where would I add the second slideshow in the HTML?
Current HTML:
<div class="slideshow-container">
<div class="mySlides fade">
<div class="numbertext">1 / 3</div>
<img src="img1.jpg" style="width:100%">
<div class="text">Caption Text</div>
</div>
<div class="mySlides fade">
<div class="numbertext">2 / 3</div>
<img src="img2.jpg" style="width:100%">
<div class="text">Caption Two</div>
</div>
<div class="mySlides fade">
<div class="numbertext">3 / 3</div>
<img src="img3.jpg" style="width:100%">
<div class="text">Caption Three</div>
</div>
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
</div>
<br>
<div style="text-align:center">
<span class="dot" onclick="currentSlide(1)"></span>
<span class="dot" onclick="currentSlide(2)"></span>
<span class="dot" onclick="currentSlide(3)"></span>
</div>
<button>Switch Slideshow</button>
Current CSS:
/* Slideshow container */
.slideshow-container {
max-width: 1000px;
position: relative;
margin: auto;
}
/* Next & previous buttons */
.prev, .next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -22px;
padding: 16px;
color: white;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
}
/* Position the "next button" to the right */
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
/* On hover, add a black background color with a little bit see-through */
.prev:hover, .next:hover {
background-color: rgba(0,0,0,0.8);
}
/* Caption text */
.text {
color: #f2f2f2;
font-size: 15px;
padding: 8px 12px;
position: absolute;
bottom: 8px;
width: 100%;
text-align: center;
}
/* Number text (1/3 etc) */
.numbertext {
color: #f2f2f2;
font-size: 12px;
padding: 8px 12px;
position: absolute;
top: 0;
}
/* The dots/bullets/indicators */
.dot {
cursor:pointer;
height: 13px;
width: 13px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.active, .dot:hover {
background-color: #717171;
}
/* Fading animation */
.fade {
-webkit-animation-name: fade;
-webkit-animation-duration: 1.5s;
animation-name: fade;
animation-duration: 1.5s;
}
#-webkit-keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
#keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
Current JavaScript:
var slideIndex = 1;
showSlides(slideIndex);
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("dot");
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " active";
}
Many thanks in advance!
Well, you need to first be able to create your slideshow dynamically. Only then will you be able to swap in-and-out different slides. I tried not to refactor your existing code. Also, I did not use jQuery (which I would use personally). Just generate the markup for each slide and set it on the slides div. I had to create an inner div so that the buttons do not get overridden.
var slideshowIndex = 1;
var slideIndex = 1;
var slideshows = [
[
'http://placehold.it/500x300/f00/0ff?text=Foo',
'http://placehold.it/500x300/0f0/f0f?text=Bar',
'http://placehold.it/500x300/00f/ff0?text=Baz'
], [
'http://placehold.it/500x300/f70/07f?text=Fizz',
'http://placehold.it/500x300/0f7/f07?text=Buzz',
'http://placehold.it/500x300/70f/7f0?text=Bang'
]
];
var buttonTextArr = [ 'Show Images', 'Show Pages' ];
function createSlides(slides) {
return slides.map(function(slide, index) {
return [
'<div class="mySlides fade">',
'<div class="numbertext">' + (index + 1) + ' / ' + slides.length + '</div>',
'<img src="' + slide + '">',
'<div class="text">Caption #' + (index + 1) + '</div>',
'</div>'
].join('');
}).join('');
}
function createDots(slides) {
return slides.map(function(slide, index) {
return '<span class="dot" onclick="currentSlide(' + (index + 1) + ')"></span>'
}).join('');
}
function loadSlideshow(slides) {
document.getElementsByClassName('slideshow-slides')[0].innerHTML = createSlides(slides);
document.getElementsByClassName('dots')[0].innerHTML = createDots(slides);
}
function loadNextSlideshow() {
slideshowIndex = (slideshowIndex + 1) % 2;
loadSlideshow(slideshows[slideshowIndex]);
slideIndex = 1; // Reset index
showSlides(slideIndex);
document.getElementsByClassName('switch')[0].innerHTML = buttonTextArr[slideshowIndex];
}
loadNextSlideshow(); // Load the slideshow
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("dot");
if (n > slides.length) {
slideIndex = 1
}
if (n < 1) {
slideIndex = slides.length
}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex - 1].style.display = "block";
dots[slideIndex - 1].className += " active";
}
/* Slideshow container */
.slideshow-container {
max-width: 1000px;
position: relative;
margin: auto;
}
/* Next & previous buttons */
.prev, .next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -22px;
padding: 16px;
color: white;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
text-shadow: 0.05em 0.05em 0.25em #000;
}
/* Position the "next button" to the right */
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
/* On hover, add a black background color with a little bit see-through */
.prev:hover, .next:hover {
background-color: rgba(0, 0, 0, 0.8);
}
/* Caption text */
.text {
color: #f2f2f2;
font-size: 15px;
padding: 8px 12px;
position: absolute;
bottom: 8px;
width: 100%;
text-align: center;
}
/* Number text (1/3 etc) */
.numbertext {
color: #f2f2f2;
font-size: 12px;
padding: 8px 12px;
position: absolute;
top: 0;
}
/* The dots/bullets/indicators */
.dot {
cursor: pointer;
height: 13px;
width: 13px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.active, .dot:hover {
background-color: #717171;
}
/* Fading animation */
.fade {
-webkit-animation-name: fade;
-webkit-animation-duration: 1.5s;
animation-name: fade;
animation-duration: 1.5s;
}
#-webkit-keyframes fade {
from { opacity: 0.4 }
to { opacity: 1 }
}
#keyframes fade {
from { opacity: 0.4 }
to { opacity: 1 }
}
<div class="slideshow-container">
<div class="slideshow-slides"></div>
<a class="prev" onClick="plusSlides(-1)">❮</a>
<a class="next" onClick="plusSlides(1)">❯</a>
</div>
<br />
<div class="dots" style="text-align:center"></div>
<button class="switch" onClick="loadNextSlideshow()">Switch Slideshow</button>
Created plunker here. Please refer below link.
https://plnkr.co/edit/xso6MfwOxQJ4PlDpW90y?p=preview
HTML
<div class="slideshow-container">
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
</div>
<br>
<div style="text-align:center">
<span class="dot" onclick="currentSlide(1)"></span>
<span class="dot" onclick="currentSlide(2)"></span>
<span class="dot" onclick="currentSlide(3)"></span>
</div>
<button>Switch Slideshow</button>
JavaScript:
var slideShowIndex = 1;
var slideShows= [
[
{
'image': 'img1.jpg',
'caption': 'Caption Text'
},
{
'image': 'img1.jpg',
'caption': 'Caption Text'
},
{
'image': 'img1.jpg',
'caption': 'Caption Text'
}
],
[
{
'image': 'img1.jpg',
'caption': 'Caption Text'
},
{
'image': 'img1.jpg',
'caption': 'Caption Text'
},
{
'image': 'img1.jpg',
'caption': 'Caption Text'
},
{
'image': 'img1.jpg',
'caption': 'Caption Text'
},
{
'image': 'img1.jpg',
'caption': 'Caption Text'
}
]
]
buildSlideShow();
var slideIndex = 1;
showSlides(slideIndex);
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("dot");
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " active";
}
function buildSlideShow(){
var slideText = '';
var slides = document.getElementsByClassName("slideshow-container");
var slidesToRender = slideShows[slideShowIndex-1];
slidesToRender.forEach(function(value,index){
slideText += '<div class="mySlides fade"><div class="numbertext">'+ index+1+ '/'+slidesToRender.length + '</div><img src="'+value.image+'" style="width:100%"><div class="text">'+value.caption+'</div></div>';
});
slides[0].innerHtml = slideText;
}
hope this works for you.

Categories