Making this slider rotate infinitely - javascript

I'm trying to make this a slider for a site and I'm having trouble making this slider rotate its images. what I want to get is when I click next on the last image it would back to the first image and the same with the previous button. the code works if i make the adjustments i made into a comment. any help would be very helpful!thanks!!
< script type = "text/javascript" >
var Slider = function() {
this.initialize.apply(this, arguments)
}
Slider.prototype = {
initialize: function(slider) {
this.ul = slider.children[0]
this.li = this.ul.children
// make <ul> as large as all <li>’s
this.ul.style.width = (this.li[0].clientWidth * this.li.length) + 'px'
this.currentIndex = 0
},
goTo: function(index) {
// filter invalid indices
if (index < 0 || index > this.li.length - 1)
return
// move <ul> left
this.ul.style.left = '-' + (100 * index) + '%'
this.currentIndex = index
},
goToPrev: function() {
this.goTo(this.currentIndex - 1)
},
goToNext: function() {
/* this is the code im trying on but it wont work
if (this.currentIndex = 0) {
this.goTo(this.currentIndex + 1)
};
else if (this.currentIndex = 1) {
this.goTo(this.currentIndex + 1)
};
else if (this.currentIndex = 2) {
this.goTo(this.currentIndex + 1)
};
else*/
this.goTo(this.currentIndex - 3)
}
}
var sliders = []
$('.slider').each(function() {
sliders.push(new Slider(this))
})
.slider {
width: 400px;
height: 300px;
overflow: hidden;
}
.slider > ul {
position: relative;
left: 0;
-webkit-transition: 0.5s left;
-moz-transition: 0.5s left;
-ms-transition: 0.5s left;
-o-transition: 0.5s left;
list-style: none;
margin: 0;
padding: 0;
}
.slider > ul > li {
float: left;
width: 400px;
height: 300px;
}
<div class="slide">
<div class="slider">
<ul>
<li>
<img src="img1.jpg">
</li>
<li>
<img src="img2.jpg">
</li>
<li>
<img src="img3.jpg">
</li>
</ul>
</div>
<div class="navigation">
Prev
<a class="butnav" href="javascript:sliders[0].goTo(0)">1</a>
<a class="butnav" href="javascript:sliders[0].goTo(1)">2</a>
<a class="butnav" href="javascript:sliders[0].goTo(2)">3</a>
Next
</div>
</div>

I have made some modification in the code and it's working for me.
var Slider = function() {
this.initialize.apply(this, arguments);
};
Slider.prototype = {
initialize: function(slider) {
this.ul = slider.children[0];
this.li = this.ul.children;
// make <ul> as large as all <li>’s
this.ul.style.width = (this.li[0].clientWidth * this.li.length) + 'px';
this.currentIndex = 0;
},
goTo: function(index) {
// filter invalid indices
if (index < 0 || index > this.li.length - 1)
return;
// move <ul> left
this.ul.style.left = '-' + (100 * index) + '%';
this.currentIndex = index;
},
goToPrev: function() {
if(this.currentIndex === 0){
this.goTo(2);
}else{
this.goTo(this.currentIndex - 1);
}
},
goToNext: function() {
if(this.currentIndex === 2){
this.goTo(0);
}else{
this.goTo(this.currentIndex + 1);
}
}
};
var sliders = [];
$('.slider').each(function() {
sliders.push(new Slider(this));
});
.slider {
width: 400px;
height: 300px;
overflow: hidden;
}
.slider > ul {
position: relative;
left: 0;
-webkit-transition: 0.5s left;
-moz-transition: 0.5s left;
-ms-transition: 0.5s left;
-o-transition: 0.5s left;
list-style: none;
margin: 0;
padding: 0;
}
.slider > ul > li {
float: left;
height: 300px;
width: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="slide">
<div class="slider">
<ul>
<li>
<img src="https://pbs.twimg.com/profile_images/590405794153136128/fdGjhrrv.jpg">
</li>
<li>
<img src="https://s-media-cache-ak0.pinimg.com/originals/3c/af/cf/3cafcf31f34af16b7f833f0bd844c856.jpg">
</li>
<li>
<img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcT-l-xbQ1bUZMCrbTvm_qbAwZOdJEWYBg3e23OrLmRl72LcWhsJfQ">
</li>
</ul>
</div>
<div class="navigation">
Prev
<a class="butnav" href="javascript:sliders[0].goTo(0)">1</a>
<a class="butnav" href="javascript:sliders[0].goTo(1)">2</a>
<a class="butnav" href="javascript:sliders[0].goTo(2)">3</a>
Next
</div>
</div>

Related

Auto Show and Div automatically after a set time in jQuery

I have divs that automatically cycle to the next div and show its contents after every few seconds. The functionality works fine however, there seems to be a gap when the last div hides and the first div is meant to show as the underline in the corresponding link for the div has a slight delay- it should change immediately. I can't figure out why this is happening. Also, I am trying execute the function 5 seconds after the page has loaded .delay(5000) does not seem to work. Below is the code:
var homeLinks = ['i-t', 'o-c', 'c-f', 'i-c', 'c-u'];
var currentLink = 0;
var hovered = false;
$(".home-link").hover(function() {
hovered = true;
$('.home-' + homeLinks[currentLink]).hide();
$('[data-hover=' + homeLinks[currentLink] + ']').toggleClass('default-underline');
currentLink = homeLinks.indexOf($(this).attr('data-hover'));
$('[data-hover=' + homeLinks[currentLink] + ']').toggleClass('default-underline');
$('.home-' + homeLinks[currentLink]).show();
}, function() {
hovered = false;
});
var autoNavInterval = setInterval(autoNav, 3000);
function autoNav() {
if (hovered === false) {
$('.home-' + homeLinks[currentLink]).hide();
$('[data-hover=' + homeLinks[currentLink] + ']').toggleClass('default-underline');
currentLink++;
if (currentLink >= homeLinks.length) {
currentLink = 0;
}
$('[data-hover=' + homeLinks[currentLink] + ']').toggleClass('default-underline');
$('.home-' + homeLinks[currentLink]).show();
}
}
.left-fill {
background: #0000006b;
height: 100vh;
}
.right-fill {
background: pink;
height: 100vh;
}
.vc_col-sm-6 {
width: 50%;
float: left;
}
.pivot-nav {
list-style: none;
font-family: 'Montserrat';
text-align: left;
}
.pivot-nav li a {
font-size: 1.6rem;
font-weight: 700;
text-transform: uppercase;
display: inline-block;
position: relative;
color: #fff;
text-decoration: none;
line-height: 40px;
}
.pivot-nav li a.default-underline::after,
.pivot-nav li a:hover::after {
width: 100%;
}
.pivot-nav:hover a.default-underline:not(:hover)::after {
width: 0;
}
.pivot-nav li a::after {
bottom: 0;
content: "";
display: block;
height: 4px;
position: absolute;
background: #fff;
transition: width 0.3s ease 0s;
width: 0;
}
.home-o-c,
.home-c-f,
.home-i-c,
.home-c-u {
display: none;
}
.our-company {
clear: both;
display: block;
height: 50vh;
}
.cf2 {
clear: both;
display: block;
height: 50vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="left-fill text-left wpb_column vc_column_container vc_col-sm-6">
<div class="wpb_wrapper">
<p class="home-i-t">TEXT One</p>
<p class="home-o-c">TEXT One</p>
<p class="home-c-f">TExt for C f.</p>
<p class="home-i-c">Some more text fo i c.</p>
<p class="home-c-u">Get in touch </p>
</div>
</div>
<div class="home-fill right-fill text-right wpb_column vc_column_container vc_col-sm-6">
<div class="wpb_wrapper">
<ul class="pivot-nav">
<li class="pivot-nav-item"><a data-hover="o-c" class="home-link" href="#" data-toggle="my-scrollspy-2">O C</a></li>
<li class="pivot-nav-item"><a data-hover="c-f" class="home-link" href="#" data-toggle="my-scrollspy-2">C F</a></li>
<li class="pivot-nav-item"><a data-hover="i-c" class="home-link" href="#" data-toggle="my-scrollspy-2">I C</a></li>
<li class="pivot-nav-item" data-toggle="my-scrollspy-2"><a data-hover="c-u" class="home-link" href="#">C U</a></li>
</ul>
</div>
</div>
To start function 5 secounds after the page was loaded first you need to be sure that your script starts working after the document is ready. Use the basic jQuery function $(function () { /* code executed after the document loaded */ } );.
Than use simple javaScript function setTimeout.
The underline switched between C U and O C longer because you set the currentLink value to 0 after you iterate through every element in the array homeLinks and the 0 element would be an a with data-hover="i-t" which doesn't exist. You can remove the first string from the array or create an element in the list or set the currentLink value to 1 after you reach the homeLinks value with currentLink.
I fixed your script code to do exactly what you described with as few changes as possible:
$(function () {
var homeLinks = ['i-t', 'o-c', 'c-f', 'i-c', 'c-u'];
var currentLink = 0;
var hovered = false;
$(".home-link").hover(function () {
hovered = true;
$('.home-' + homeLinks[currentLink]).hide();
$('[data-hover=' + homeLinks[currentLink] + ']').toggleClass('default-underline');
currentLink = homeLinks.indexOf($(this).attr('data-hover'));
$('[data-hover=' + homeLinks[currentLink] + ']').toggleClass('default-underline');
$('.home-' + homeLinks[currentLink]).show();
}, function (event) {
hovered = false;
currentLink = 0;
$('.wpb_wrapper p').hide();
$(event.target).toggleClass('default-underline');
});
setTimeout(() => {
var autoNavInterval = setInterval(autoNav, 1000);
}, 1000);
function autoNav() {
if (hovered === false) {
$('.home-' + homeLinks[currentLink]).hide();
$('[data-hover=' + homeLinks[currentLink] + ']').toggleClass('default-underline');
currentLink++;
if (currentLink >= homeLinks.length) {
currentLink = 1;
}
$('[data-hover=' + homeLinks[currentLink] + ']').toggleClass('default-underline');
$('.home-' + homeLinks[currentLink]).show();
}
else {
}
}
});

I would like to know how to fix Touch-friendly slider

I'd like to use the script "touch-friendly slider" by KEVIN Foley. But there is a problem. When I add a 5 slide, I can't slide further. The script stops working at Transform: translate -600px
I've tried to find a solution for a long time, but I couldn't.
Original Code
https://css-tricks.com/the-javascript-behind-touch-friendly-sliders/
This my code (Edit)
https://codepen.io/anon/pen/KBbbmY
$(function(){
if (navigator.msMaxTouchPoints) {
$('#slider').addClass('ms-touch');
$('#slider').on('scroll', function() {
$('.slide-image').css('transform','translate3d(-300px,0,0)');
});
} else {
var slider = {
el: {
slider: $("#slider"),
holder: $(".holder"),
imgSlide: $(".slide-image")
},
slideWidth:300,
touchstartx: undefined,
touchmovex: undefined,
movex: undefined,
index: 0,
longTouch: undefined,
init: function() {
this.bindUIEvents();
},
bindUIEvents: function() {
this.el.holder.on("touchstart", function(event) {
slider.start(event);
});
this.el.holder.on("touchmove", function(event) {
slider.move(event);
});
this.el.holder.on("touchend", function(event) {
slider.end(event);
});
},
start: function(event) {
// Test for flick.
this.longTouch = false;
setTimeout(function() {
window.slider.longTouch = true;
}, 250);
// Get the original touch position.
this.touchstartx = event.originalEvent.touches[0].pageX;
// The movement gets all janky if there's a transition on the elements.
$('.animate').removeClass('animate');
},
move: function(event) {
// Continuously return touch position.
this.touchmovex = event.originalEvent.touches[0].pageX;
// Calculate distance to translate holder.
this.movex = this.index*this.slideWidth + (this.touchstartx - this.touchmovex);
// Defines the speed the images should move at.
var panx = 100-this.movex/6;
if (this.movex <= 2400) { // Makes the holder stop moving when there is no more content.
this.el.holder.css('transform','translate3d(-' + this.movex + 'px,0,0)');
}
if (panx < 100) { // Corrects an edge-case problem where the background image moves without the container moving.
this.el.imgSlide.css('transform','translate3d(-' + panx + 'px,0,0)');
}
},
end: function(event) {
// Calculate the distance swiped.
var absMove = Math.abs(this.index*this.slideWidth - this.movex);
// Calculate the index. All other calculations are based on the index.
if (absMove > this.slideWidth/2 || this.longTouch === false) {
if (this.movex > this.index*this.slideWidth && this.index < 2) {
this.index++;
} else if (this.movex < this.index*this.slideWidth && this.index > 0) {
this.index--;
}
}
// Move and animate the elements.
this.el.holder.addClass('animate').css('transform', 'translate3d(-' + this.index*this.slideWidth + 'px,0,0)');
// this.el.imgSlide.addClass('animate').css('transform', 'translate3d(-' + 100-this.index*50 + 'px,0,0)');
}
};
slider.init();
}
});
#import url(https://fonts.googleapis.com/css?family=Josefin+Slab:100);
.animate {
transition: transform 0.3s ease-out;
}
html,
body {
height: 100%;
}
body {
margin: 0;
padding: 0;
overflow: hidden;
}
.slider-wrap {
width: 300px;
height: 500px;
position: absolute;
left: 50%;
margin-left: -150px;
top: 50%;
margin-top: -225px;
}
.slider {
width: 100%;
height: 100%;
overflow: hidden;
}
.ms-touch.slider {
overflow-x: scroll;
overflow-y: hidden;
-ms-overflow-style: none;
/* Hides the scrollbar. */
-ms-scroll-chaining: none;
/* Prevents Metro from swiping to the next tab or app. */
-ms-scroll-snap-type: mandatory;
/* Forces a snap scroll behavior on your images. */
-ms-scroll-snap-points-x: snapInterval(0%, 100%);
/* Defines the y and x intervals to snap to when scrolling. */
}
.holder {
width: 1500px;
max-height: 500px;
height: 100%;
overflow-y: hidden;
}
.slide-wrapper {
width: 300px;
height: 100%;
float: left;
height: 500px;
position: relative;
overflow: hidden;
}
.slide {
height: 100%;
position: relative;
}
.temp {
position: absolute;
z-index: 1;
color: white;
font-size: 100px;
bottom: 15px;
left: 15px;
font-family: 'Josefin Slab', serif;
font-weight: 100;
}
.slide img {
position: absolute;
z-index: 0;
transform: translatex(-100px);
}
.slide:before {
content: "";
position: absolute;
z-index: 1;
bottom: 0;
left: 0;
width: 100%;
height: 40%;
background: linear-gradient(transparent, black);
}
.slide div {
width: 300px;
height: 500px;
z-index: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slider-wrap">
<div class="slider" id="slider">
<div class="holder">
<div class="slide-wrapper">
<div class="slide"><img class="slide-image" src="http://farm8.staticflickr.com/7347/8731666710_34d07e709e_z.jpg" /></div>
<span class="temp">74</span>
</div>
<div class="slide-wrapper">
<div class="slide"><img class="slide-image" src="http://farm8.staticflickr.com/7384/8730654121_05bca33388_z.jpg" /></div>
<span class="temp">64</span>
</div>
<div class="slide-wrapper">
<div class="slide"><img class="slide-image" src="http://farm8.staticflickr.com/7382/8732044638_9337082fc6_z.jpg" /></div>
<span class="temp">82</span>
</div>
<div class="slide-wrapper">
<div class="slide"><img class="slide-image" src="http://farm8.staticflickr.com/7382/8732044638_9337082fc6_z.jpg" /></div>
<span class="temp">92</span>
</div>
<div class="slide-wrapper">
<div class="slide"><img class="slide-image" src="http://farm8.staticflickr.com/7382/8732044638_9337082fc6_z.jpg" /></div>
<span class="temp">102</span>
</div>
</div>
</div>
</div>
or
https://jsfiddle.net/nuengwispy/30dp4n8j/1/
when you test "F12" and "Ctrl+Shift+M"
I would like to know how to fix
"touch-friendly slider" until the end slide.
Finally, i choose to use the code of "weixhen" and i modified a bit.
when your test please: F12 and Ctrl+Shift+M
$(function() {
var width_container_touch_slide_recommend = 380;
var div_touch_slide_recommend = $("#touch_slide_recommend");
var items_touch_slide_recommend = $("#ul_touch_slide_recommend > li");
var length_touch_slide_recommend = items_touch_slide_recommend.length;
var star_touch_slide_recommend = 0;
var distance_touch_slide_recommend = 0;
var stop_touch_slide_recommend = 0;
var max_distance_recommend = ((items_touch_slide_recommend.length) * width_container_touch_slide_recommend) - width_container_touch_slide_recommend;
div_touch_slide_recommend.css("width", width_container_touch_slide_recommend + "px");
window.touch_slide_recommend.addEventListener("touchstart", function(e) {
star_touch_slide_recommend = e.touches[0].clientX;
window.ul_touch_slide_recommend.style.transition = '0ms';
});
window.touch_slide_recommend.addEventListener('touchmove', function(e) {
distance_touch_slide_recommend = stop_touch_slide_recommend + star_touch_slide_recommend - e.touches[0].clientX
window.ul_touch_slide_recommend.style.transform = 'translateX(' + (-distance_touch_slide_recommend) + 'px)';
});
window.touch_slide_recommend.addEventListener('touchend', function(e) {
fluentslide_recommend();
stop_touch_slide_recommend = distance_touch_slide_recommend;
});
var fluentslide_recommend = function() {
index = Math.round(distance_touch_slide_recommend / width_container_touch_slide_recommend);
if (distance_touch_slide_recommend % width_container_touch_slide_recommend !== 0) {
distance_touch_slide_recommend = index * width_container_touch_slide_recommend;
}
if (distance_touch_slide_recommend < 0) {
distance_touch_slide_recommend = 0;
}
if (distance_touch_slide_recommend > max_distance_recommend) {
distance_touch_slide_recommend = max_distance_recommend;
}
window.ul_touch_slide_recommend.style.transition = '500ms';
window.ul_touch_slide_recommend.style.transform = 'translateX(' + (-distance_touch_slide_recommend) + 'px)';
}
});
$(function() {
var width_container_touch_slide_best = 480;
var div_touch_slide_best = $("#touch_slide_best");
var items_touch_slide_best = $("#ul_touch_slide_best > li");
var length_touch_slide_best = items_touch_slide_best.length;
var star_touch_slide_best = 0;
var distance_touch_slide_best = 0;
var stop_touch_slide_best = 0;
var max_distance_best = ((items_touch_slide_best.length) * width_container_touch_slide_best) - width_container_touch_slide_best;
div_touch_slide_best.css("width", width_container_touch_slide_best + "px");
window.touch_slide_best.addEventListener("touchstart", function(e) {
star_touch_slide_best = e.touches[0].clientX;
window.ul_touch_slide_best.style.transition = '0ms';
});
window.touch_slide_best.addEventListener('touchmove', function(e) {
distance_touch_slide_best = stop_touch_slide_best + star_touch_slide_best - e.touches[0].clientX
window.ul_touch_slide_best.style.transform = 'translateX(' + (-distance_touch_slide_best) + 'px)';
});
window.touch_slide_best.addEventListener('touchend', function(e) {
fluentslide_best();
stop_touch_slide_best = distance_touch_slide_best;
});
var fluentslide_best = function() {
index = Math.round(distance_touch_slide_best / width_container_touch_slide_best);
if (distance_touch_slide_best % width_container_touch_slide_best !== 0) {
distance_touch_slide_best = index * width_container_touch_slide_best;
}
if (distance_touch_slide_best < 0) {
distance_touch_slide_best = 0;
}
if (distance_touch_slide_best > max_distance_best) {
distance_touch_slide_best = max_distance_best;
}
window.ul_touch_slide_best.style.transition = '500ms';
window.ul_touch_slide_best.style.transform = 'translateX(' + (-distance_touch_slide_best) + 'px)';
}
});
* {
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
body {
margin: 0px;
}
[id^="touch_slide_"] {
margin-left: auto;
margin-right: auto;
overflow-x: hidden;
position: relative;
}
[id^="ul_touch_slide_"] {
margin: 0;
padding: 0;
list-style: none;
display: flex;
flex-flow: row nowrap;
justify-content: flex-start;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h1>Recommend</h1>
<div id="touch_slide_recommend">
<ul id="ul_touch_slide_recommend">
<li><img src="http://placehold.it/380x285" alt=""></li>
<li><img src="http://placehold.it/380x285" alt=""></li>
<li><img src="http://placehold.it/380x285" alt=""></li>
<li><img src="http://placehold.it/380x285" alt=""></li>
<li><img src="http://placehold.it/380x285" alt=""></li>
</ul>
</div>
<h1>Best Seller</h1>
<div id="touch_slide_best">
<ul id="ul_touch_slide_best">
<li><img src="http://placehold.it/480x285" alt=""></li>
<li><img src="http://placehold.it/480x285" alt=""></li>
<li><img src="http://placehold.it/480x285" alt=""></li>
<li><img src="http://placehold.it/480x285" alt=""></li>
<li><img src="http://placehold.it/480x285" alt=""></li>
</ul>
</div>
of
http://jsfiddle.net/nuengwispy/0tmsLz2p/
original code: https://codepen.io/weixhen/pen/QggGVM (thanks weixhen)

fade in or out depending on active class, fade in works, out does not

This is probably best viewed in the fiddle here.
This is a simple fade in/out slideshow for a portfolio. The displayed slide has a class "active". It should fade out before the next slide fades in. Instead it disappears instantly. The fade in of the next slide is working fine.
This is the basic html code.
var x = document.getElementById("inner-portfolio-wrapper").childElementCount;
var j = 1;
var k;
function clickMe() {
if (x > 1) {
if (j === x) {
j = 1;
k = x;
} else {
k = j;
j++;
}
console.log("j = " + j);
console.log("k = " + k);
document.getElementById("portfolio-item-" + k).style.display = "none";
document.getElementById("portfolio-item-" + j).style.display = "block";
document.getElementById("portfolio-item-" + j).classList.add("active");
document.getElementById("portfolio-item-" + k).classList.remove("active");
}
}
#inner-portfolio-wrapper {
position: relative;
width: 150px;
height: 50px;
}
.portfolio-item {
display: none;
animation: fadeIn 2s;
}
.portfolio-item .active {
display: block;
animation: fadeOut 2s;
}
.portfolio-item:first-child {
display: block;
}
#keyframes fadeOut {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
#keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
<div id="inner-portfolio-wrapper">
<div id="portfolio-item-1" class="portfolio-item">
<h2>
ITEM 1
</h2>
</div>
<div id="portfolio-item-2" class="portfolio-item">
<h2>
ITEM 2
</h2>
</div>
<div id="portfolio-item-3" class="portfolio-item">
<h2>
ITEM 3
</h2>
</div>
</div>
<button type="button" onclick="clickMe()">
Click Me
</button>
Any help to get the fade out working would be appreciated. Everything else is working just fine.
For now, fadeOut animation doesn't work because click on button immediately removes .active from the item and it gets style display: none.
To get the desired effect the only thing your onClick function has to do - is to trigger fadeOut animation. All next actions have to be called as callback of animationEnd event.
You also need to make some changes in styles:
.portfolio-item {
display: none;
}
.portfolio-item.active {
display: block;
animation: fadeIn 2s;
}
.portfolio-item.active.out {
display: block;
animation: fadeOut 2s;
}
And finally, it works:
//detect the supported event property name and assign it to variable
// Function from David Walsh: http://davidwalsh.name/css-animation-callback
function whichAnimationEvent() {
var t,
el = document.createElement("fakeelement");
var animations = {
"animation": "animationend",
"OAnimation": "oAnimationEnd",
"MozAnimation": "animationend",
"WebkitAnimation": "webkitAnimationEnd"
}
for (t in animations) {
if (el.style[t] !== undefined) {
return animations[t];
}
}
}
var animationEvent = whichAnimationEvent();
//Declare global variables
var total = document.getElementById("inner-portfolio-wrapper").childElementCount;
var currentNum = 1
var nextNum;
//Get all portfolio items add add them an event listener
var items = document.getElementById("inner-portfolio-wrapper").children
for (var i = 0; i < items.length; i++) {
items[i].addEventListener(animationEvent, function(e) {
if (e.animationName === 'fadeOut') {
this.classList.toggle('out')
this.classList.toggle('active');
document.getElementById("portfolio-item-" + nextNum).classList.toggle('active')
currentNum = nextNum
}
})
}
//When page loaded make first porfolio item active
items[0].classList.add("active");
function clickMe() {
if (total > 1) {
var currentElement = document.getElementById("portfolio-item-" + currentNum);
nextNum = (currentNum === total) ? 1 : currentNum + 1
currentElement.classList.toggle('out')
}
}
#inner-portfolio-wrapper {
position: relative;
width: 150px;
height: 50px;
}
.portfolio-item {
display: none;
}
.portfolio-item.active {
display: block;
animation: fadeIn 2s;
}
.portfolio-item.active.out {
display: block;
animation: fadeOut 2s;
}
#keyframes fadeOut {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
#keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
<div id="inner-portfolio-wrapper">
<div id="portfolio-item-1" class="portfolio-item">
<h2>
ITEM 1
</h2>
</div>
<div id="portfolio-item-2" class="portfolio-item">
<h2>
ITEM 2
</h2>
</div>
<div id="portfolio-item-3" class="portfolio-item">
<h2>
ITEM 3
</h2>
</div>
</div>
<button type="button" onclick="clickMe()">
Click Me
</button>

Javascript Slider doesn't work correctly with transition end

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

How to build simple jQuery image slider with sliding or opacity effect?

Some of us might not want to use ready plugins because of their high sizes and possibilty of creating conflicts with current javascript.
I was using light slider plugins before but when customer gives modular revise, it became really hard to manipulate. Then I aim to build mine for customising it easily. I believe sliders shouldn't be that complex to build from beginning.
What is a simple and clean way to build jQuery image slider?
Before inspecting examples, you should know two jQuery functions which i used most.
index() returns value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.
eq() selects of an element based on its position (index value).
Basicly i take selected trigger element's index value and match this value on images with eq method.
- FadeIn / FadeOut effect.
- Sliding effect.
- alternate Mousewheel response.
​html sample:
<ul class="images">
<li>
<img src="images/1.jpg" alt="1" />
</li>
<li>
<img src="images/2.jpg" alt="2" />
</li>
...
</ul>
<ul class="triggers">
<li>1</li>
<li>2</li>
...
</ul>
<span class="control prev">Prev</span>
<span class="control next">Next</span>
OPACITY EFFECT: jsFiddle.
css trick: overlapping images with position:absolute
ul.images { position:relative; }
ul.images li { position:absolute; }
jQuery:
var target;
var triggers = $('ul.triggers li');
var images = $('ul.images li');
var lastElem = triggers.length-1;
triggers.first().addClass('active');
images.hide().first().show();
function sliderResponse(target) {
images.fadeOut(300).eq(target).fadeIn(300);
triggers.removeClass('active').eq(target).addClass('active');
}
SLIDING EFFECT: jsFiddle.
css trick: with double wrapper and use child as mask
.mask { float:left; margin:40px; width:270px; height:266px; overflow:hidden; }
ul.images { position:relative; top:0px;left:0px; }
/* this width must be total of the images, it comes from jquery */
ul.images li { float:left; }
jQuery:
var target;
var triggers = $('ul.triggers li');
var images = $('ul.images li');
var lastElem = triggers.length-1;
var mask = $('.mask ul.images');
var imgWidth = images.width();
triggers.first().addClass('active');
mask.css('width', imgWidth*(lastElem+1) +'px');
function sliderResponse(target) {
mask.stop(true,false).animate({'left':'-'+ imgWidth*target +'px'},300);
triggers.removeClass('active').eq(target).addClass('active');
}
Common jQuery response for both slider:
( triggers + next/prev click and timing )
triggers.click(function() {
if ( !$(this).hasClass('active') ) {
target = $(this).index();
sliderResponse(target);
resetTiming();
}
});
$('.next').click(function() {
target = $('ul.triggers li.active').index();
target === lastElem ? target = 0 : target = target+1;
sliderResponse(target);
resetTiming();
});
$('.prev').click(function() {
target = $('ul.triggers li.active').index();
lastElem = triggers.length-1;
target === 0 ? target = lastElem : target = target-1;
sliderResponse(target);
resetTiming();
});
function sliderTiming() {
target = $('ul.triggers li.active').index();
target === lastElem ? target = 0 : target = target+1;
sliderResponse(target);
}
var timingRun = setInterval(function() { sliderTiming(); },5000);
function resetTiming() {
clearInterval(timingRun);
timingRun = setInterval(function() { sliderTiming(); },5000);
}
Here is a simple and easy to understand code for Creating image slideshow using JavaScript without using Jquery.
<script language="JavaScript">
var i = 0; var path = new Array();
// LIST OF IMAGES
path[0] = "image_1.gif";
path[1] = "image_2.gif";
path[2] = "image_3.gif";
function swapImage() { document.slide.src = path[i];
if(i < path.length - 1) i++;
else i = 0; setTimeout("swapImage()",3000);
} window.onload=swapImage;
</script>
<img height="200" name="slide" src="image_1.gif" width="400" />
I have recently created a solution with a gallery of images and a slider that apears when an image is clicked.
Take a look at the code here: GitHub Code
And a live example here: Code Example
var CreateGallery = function(parameters) {
var self = this;
this.galleryImages = [];
this.galleryImagesSrcs = [];
this.galleryImagesNum = 0;
this.counter;
this.galleryTitle = parameters.galleryTitle != undefined ? parameters.galleryTitle : 'Gallery image';
this.maxMobileWidth = parameters.maxMobileWidth != undefined ? parameters.maxMobileWidth : 768;
this.numMobileImg = parameters.numMobileImg != undefined ? parameters.numMobileImg : 2;
this.maxTabletWidth = parameters.maxTabletWidth != undefined ? parameters.maxTabletWidth : 1024;
this.numTabletImg = parameters.numTabletImg != undefined ? parameters.numTabletImg : 3;
this.addModalGallery = function(gallerySelf = self){
var $div = $(document.createElement('div')).attr({
'id': 'modal-gallery'
}).append($(document.createElement('div')).attr({
'class': 'header'
}).append($(document.createElement('button')).attr({
'class': 'close-button',
'type': 'button'
}).html('×')
).append($(document.createElement('h2')).text(gallerySelf.galleryTitle))
).append($(document.createElement('div')).attr({
'class': 'text-center'
}).append($(document.createElement('img')).attr({
'id': 'gallery-img'
})
).append($(document.createElement('button')).attr({
'class': 'prev-button',
'type': 'button'
}).html('◄')
).append($(document.createElement('button')).attr({
'class': 'next-button',
'type': 'button'
}).html('►')
)
);
parameters.element.after($div);
};
$(document).on('click', 'button.prev-button', {self: self}, function() {
var $currImg = self.counter >= 1 ? self.galleryImages[--self.counter] : self.galleryImages[self.counter];
var $currHash = self.galleryImagesSrcs[self.counter];
var $src = $currImg.src;
window.location.hash = $currHash;
$('img#gallery-img').attr('src', $src);
$('div#modal-gallery h2').text(self.galleryTitle + ' ' + (self.counter + 1));
});
$(document).on('click', 'button.next-button', {self: self}, function() {
var $currImg = self.counter < (self.galleryImagesNum - 1) ? self.galleryImages[++self.counter] : self.galleryImages[self.counter];
var $currHash = self.galleryImagesSrcs[self.counter];
var $src = $currImg.src;
window.location.hash = $currHash;
$('img#gallery-img').attr('src', $src);
$('div#modal-gallery h2').text(self.galleryTitle + ' ' + (self.counter + 1));
});
$(document).on('click', 'div#modal-gallery button.close-button', function() {
$('#modal-gallery').css('position', 'relative');
$('#modal-gallery').hide();
$('body').css('overflow', 'visible');
});
parameters.element.find('a').on('click', {self: self}, function(event) {
event.preventDefault();
$('#modal-gallery').css('position', 'fixed');
$('#modal-gallery').show();
$('body').css('overflow', 'hidden');
var $currHash = this.hash.substr(1);
self.counter = self.galleryImagesSrcs.indexOf($currHash);
var $src = $currHash;
window.location.hash = $currHash;
$('img#gallery-img').attr('src', $src);
$('div#modal-gallery h2').text(self.galleryTitle + ' ' + (self.counter + 1));
});
this.sizeGallery = function(gallerySelf = self) {
var $modalGallery = $(document).find("div#modal-gallery");
if($modalGallery.length <= 0) {
this.addModalGallery();
}
var $windowWidth = $(window).width();
var $parentWidth = parameters.element.width();
var $thumbnailHref = parameters.element.find('img:first').attr('src');
if($windowWidth < gallerySelf.maxMobileWidth) {
var percentMobile = Math.floor(100 / gallerySelf.numMobileImg);
var emMobile = 0;
var pxMobile = 2;
// var emMobile = gallerySelf.numMobileImg * 0.4;
// var pxMobile = gallerySelf.numMobileImg * 2;
parameters.element.find('img').css('width', 'calc('+percentMobile+'% - '+emMobile+'em - '+pxMobile+'px)');
} else if($windowWidth < gallerySelf.maxTabletWidth) {
var percentTablet = Math.floor(100 / gallerySelf.numTabletImg);
var emTablet = 0;
var pxTablet = 2;
// var emTablet = gallerySelf.numMobileImg * 0.4;
// var pxTablet = gallerySelf.numMobileImg * 2;
parameters.element.find('img').css('width', 'calc('+percentTablet+'% - '+emTablet+'em - '+pxTablet+'px)');
} else {
var $thumbImg = new Image();
$thumbImg.src = $thumbnailHref;
$thumbImg.onload = function() {
var $thumbnailWidth = this.width;
if($parentWidth > 0 && $thumbnailWidth > 0) {
parameters.element.find('img').css('width', (Math.ceil($thumbnailWidth * 100 / $parentWidth))+'%');
}
};
}
};
this.startGallery = function(gallerySelf = self) {
parameters.element.find('a').each(function(index, el) {
var $currHash = el.hash.substr(1);
var $img = new Image();
$img.src = $currHash;
gallerySelf.galleryImages.push($img);
gallerySelf.galleryImagesSrcs.push($currHash);
});
this.galleryImagesNum = this.galleryImages.length;
};
this.sizeGallery();
this.startGallery();
};
var myGallery;
$(window).on('load', function() {
myGallery = new CreateGallery({
element: $('#div-gallery'),
maxMobileWidth: 768,
numMobileImg: 2,
maxTabletWidth: 1024,
numTabletImg: 3
});
});
$(window).on('resize', function() {
myGallery.sizeGallery();
});
#div-gallery {
text-align: center;
}
#div-gallery img {
margin-right: auto;
margin-left: auto;
}
div#modal-gallery {
top: 0;
left: 0;
width: 100%;
max-width: none;
height: 100vh;
min-height: 100vh;
margin-left: 0;
border: 0;
border-radius: 0;
z-index: 1006;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
display: none;
background-color: #fefefe;
position: relative;
margin-right: auto;
overflow-y: auto;
padding: 0;
}
div#modal-gallery div.header {
position: relative;
}
div#modal-gallery div.header h2 {
margin-left: 1rem;
}
div#modal-gallery div.header button.close-button {
position: absolute;
top: calc(50% - 1em);
right: 1rem;
}
div#modal-gallery img {
display: block;
max-width: 98%;
max-height: calc(100vh - 5em);
margin-right: auto;
margin-left: auto;
}
div#modal-gallery div.text-center {
position: relative;
}
button.close-button {
display: inline-block;
padding: 6px 12px;
margin-bottom: 0;
font-size: 20px;
font-weight: 400;
line-height: 1.42857143;
text-align: center;
white-space: nowrap;
vertical-align: middle;
-ms-touch-action: manipulation;
touch-action: manipulation;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background-image: none;
border: 1px solid transparent;
border-radius: 4px;
color: #333;
background-color: #fff;
border-color: #ccc;
}
button.close-button:hover, button.close-button:focus {
background-color: #ddd;
}
button.next-button:hover, button.prev-button:hover, button.next-button:focus, button.prev-button:focus {
color: #fff;
text-decoration: none;
filter: alpha(opacity=90);
outline: 0;
opacity: .9;
}
button.next-button, button.prev-button {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 15%;
font-size: 20px;
color: #fff;
text-align: center;
text-shadow: 0 1px 2px rgba(0,0,0,.6);
background-color: rgba(0,0,0,0);
filter: alpha(opacity=50);
opacity: .5;
border: none;
}
button.next-button {
right: 0;
left: auto;
background-image: -webkit-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);
background-image: -o-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);
background-image: -webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.0001)),to(rgba(0,0,0,.5)));
background-image: linear-gradient(to right,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);
background-repeat: repeat-x;
}
button.prev-button {
background-image: -webkit-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);
background-image: -o-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);
background-image: -webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.5)),to(rgba(0,0,0,.0001)));
background-image: linear-gradient(to right,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);
background-repeat: repeat-x;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="div-gallery">
<img src="http://placehold.it/300x300/ff0000/000000?text=Gallery+image+1" alt="">
<img src="http://placehold.it/300x300/ff4000/000000?text=Gallery+image+2" alt="">
<img src="http://placehold.it/300x300/ff8000/000000?text=Gallery+image+3" alt="">
<img src="http://placehold.it/300x300/ffbf00/000000?text=Gallery+image+4" alt="">
<img src="http://placehold.it/300x300/ffff00/000000?text=Gallery+image+5" alt="">
<img src="http://placehold.it/300x300/bfff00/000000?text=Gallery+image+6" alt="">
<img src="http://placehold.it/300x300/80ff00/000000?text=Gallery+image+7" alt="">
<img src="http://placehold.it/300x300/40ff00/000000?text=Gallery+image+8" alt="">
<img src="http://placehold.it/300x300/00ff00/000000?text=Gallery+image+9" alt="">
<img src="http://placehold.it/300x300/00ff40/000000?text=Gallery+image+10" alt="">
<img src="http://placehold.it/300x300/00ff80/000000?text=Gallery+image+11" alt="">
<img src="http://placehold.it/300x300/00ffbf/000000?text=Gallery+image+12" alt="">
<img src="http://placehold.it/300x300/00ffff/000000?text=Gallery+image+13" alt="">
<img src="http://placehold.it/300x300/00bfff/000000?text=Gallery+image+14" alt="">
<img src="http://placehold.it/300x300/0080ff/000000?text=Gallery+image+15" alt="">
<img src="http://placehold.it/300x300/0040ff/000000?text=Gallery+image+16" alt="">
</div>
Checkout this whole bunch of code to build simple jquery image slider. Copy and save this file to local machine and test it. You can modify it according to your requirement.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
var current_img = 1;
var i;
$(document).ready(function(){
var imgs = $("#image").find("img");
function show_img(){
for (i = 1; i < imgs.length+1; i++) {
if(i == current_img){
$(imgs[i-1]).show();
}else{
$(imgs[i-1]).hide()
}
}
}
$("#prev").click(function(){
if(current_img == 1){
current_img = imgs.length;
}else{
current_img = current_img - 1
}
show_img();
});
$("#next").click(function(){
if(current_img == imgs.length){
current_img = 1;
}else{
current_img = current_img + 1
}
show_img();
});
});
</script>
</head>
<body>
<div style="margin-top: 100px;"></div>
<div class="container">
<div class="col-sm-3">
<button type="button" id="prev" class="btn">Previous</button>
</div>
<div class="col-sm-6">
<div id="image">
<img src="https://www.w3schools.com/html/pulpitrock.jpg" alt="image1">
<img src="https://www.w3schools.com/cSS/img_forest.jpg" alt="image2" hidden="true" style="max-width: 500px;">
<img src="https://www.w3schools.com/html/img_chania.jpg" alt="image3" hidden="true">
</div>
</div>
<div class="col-sm-3">
<button type="button" id="next" class="btn">Next</button>
</div>
</div>
</body>
</html>
I have written a tutorial on creating a slideshow, The tutorial page
In case the link becomes invalid I have included the code in my answer below.
the html:
<div id="slideShow">
<div id="slideShowWindow">
<div class="slide">
<img src="”img1.png”/">
<div class="slideText">
<h2>The Slide Title</h2>
<p>This is the slide text</p>
</div> <!-- </slideText> -->
</div> <!-- </slide> repeat as many times as needed -->
</div> <!-- </slideShowWindow> -->
</div> <!-- </slideshow> -->
css:
img {
display: block;
width: 100%;
height: auto;
}
p{
background:none;
color:#ffffff;
}
#slideShow #slideShowWindow {
width: 650px;
height: 450px;
margin: 0;
padding: 0;
position: relative;
overflow:hidden;
margin-left: auto;
margin-right:auto;
}
#slideShow #slideShowWindow .slide {
margin: 0;
padding: 0;
width: 650px;
height: 450px;
float: left;
position: relative;
margin-left:auto;
margin-right: auto;
}
#slideshow #slideshowWindow .slide, .slideText {
position:absolute;
bottom:18px;
left:0;
width:100%;
height:auto;
margin:0;
padding:0;
color:#ffffff;
font-family:Myriad Pro, Arial, Helvetica, sans-serif;
}
.slideText {
background: rgba(128, 128, 128, 0.49);
}
#slideshow #slideshowWindow .slide .slideText h2,
#slideshow #slideshowWindow .slide .slideText p {
margin:10px;
padding:15px;
}
.slideNav {
display: block;
text-indent: -10000px;
position: absolute;
cursor: pointer;
}
#leftNav {
left: 0;
bottom: 0;
width: 48px;
height: 48px;
background-image: url("../Images/plus_add_minus.png");
background-repeat: no-repeat;
z-index: 10;
}
#rightNav {
right: 0;
bottom: 0;
width: 48px;
height: 48px;
background-image: url("../Images/plus_add_green.png");
background-repeat: no-repeat;
z-index: 10; }
jQuery:
$(document).ready(function () {
var currentPosition = 0;
var slideWidth = 650;
var slides = $('.slide');
var numberOfSlides = slides.length;
var slideShowInterval;
var speed = 3000;
//Assign a timer, so it will run periodically
slideShowInterval = setInterval(changePosition, speed);
slides.wrapAll('<div id="slidesHolder"></div>');
slides.css({ 'float': 'left' });
//set #slidesHolder width equal to the total width of all the slides
$('#slidesHolder').css('width', slideWidth * numberOfSlides);
$('#slideShowWindow')
.prepend('<span class="slideNav" id="leftNav">Move Left</span>')
.append('<span class="slideNav" id="rightNav">Move Right</span>');
manageNav(currentPosition);
//tell the buttons what to do when clicked
$('.slideNav').bind('click', function () {
//determine new position
currentPosition = ($(this).attr('id') === 'rightNav')
? currentPosition + 1 : currentPosition - 1;
//hide/show controls
manageNav(currentPosition);
clearInterval(slideShowInterval);
slideShowInterval = setInterval(changePosition, speed);
moveSlide();
});
function manageNav(position) {
//hide left arrow if position is first slide
if (position === 0) {
$('#leftNav').hide();
}
else {
$('#leftNav').show();
}
//hide right arrow is slide position is last slide
if (position === numberOfSlides - 1) {
$('#rightNav').hide();
}
else {
$('#rightNav').show();
}
}
//changePosition: this is called when the slide is moved by the timer and NOT when the next or previous buttons are clicked
function changePosition() {
if (currentPosition === numberOfSlides - 1) {
currentPosition = 0;
manageNav(currentPosition);
} else {
currentPosition++;
manageNav(currentPosition);
}
moveSlide();
}
//moveSlide: this function moves the slide
function moveSlide() {
$('#slidesHolder').animate({ 'marginLeft': slideWidth * (-currentPosition) });
}
});

Categories

Resources