I've recently started work on a basic landing-page website. Part of the page is a basic image slider with both the auto-nav and the manual nav being powered by JS. I got everything working but for one thing: I just can't figure out how to get the smooth transition between images - as seen in this example - to work. I figured out the problem after reading some related questions on Stackoverflow: To make the Slideshow work I'm using slides[i].style.display = "none"; and slides[slideIndex-1].style.display = "block"; to update the css code handling the 'display' element - this over rights the 'transition: 2s' css code one would need for the simple slide animation as seen in the video.
As I'm terribly new to Web development I could not wrap my head around possible solutions posted here on Stackoverflow and would really appreciate anyone that could help me out with an answer to my specific problem or an alternative way to solve it.
Cheers,
Jerome
var slideIndex = 1;
showSlides(slideIndex);
// Next/previous controls
function plusSlides(n) {
showSlides(slideIndex += n);
}
// Thumbnail image controls
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("item");
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";
}
//automatic
var slideIndexAuto = 0;
showSlidesAuto();
function showSlidesAuto() {
var i;
var slides = document.getElementsByClassName("item");
var dots = document.getElementsByClassName("dot");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
dots[i].className = dots[i].className.replace(" active", "");
}
slideIndexAuto++;
if (slideIndexAuto > slides.length) {
slideIndexAuto = 1
}
slides[slideIndexAuto - 1].style.display = "block";
dots[slideIndexAuto - 1].className += " active";
setTimeout(showSlidesAuto, 5000);
}
.slider {
width: 65%;
max-width: 940px;
height: 500px;
border-radius: 0.25rem;
position: relative;
overflow: hidden;
}
.slider .left-slide,
.slider .right-slide {
position: absolute;
height: 40px;
width: 40px;
background-color: #444444;
border-radius: 50%;
color: #ffffff;
font-size: 20px;
top: 50%;
cursor: pointer;
margin-top: -20px;
text-align: center;
line-height: 40px;
}
.slider .left-slide:hover,
.slider .right-slide:hover {
box-shadow: 0px 0px 10px black;
background-color: #29a8e2;
}
.slider .left-slide {
left: 30px;
}
.slider .right-slide {
right: 30px;
}
.slider .slider-items .item img {
width: 100%;
height: 500px;
display: block;
}
.slider .slider-items .item {
position: relative;
transition: 4s;
}
.slider .slider-items .item .caption {
position: absolute;
width: 100%;
height: 100%;
bottom: 0px;
left: 0px;
background-color: rgba(0, 0, 0, .5);
}
<div class="slider">
<div class="slider-items">
<div class="item fade">
<img src="/images/cs-slider-high.jpg" />
<div class="caption">
<p class="caption-text">COMING</p>
<p class="caption-text">OKTOBER 10th</p>
</div>
</div>
<div class="item fade">
<img src="/images/building-slider.jpg" />
<div class="caption">
<p class="caption-text-2">Blackstoneroad 109</br>
</p>
</div>
</div>
<div class="item fade">
<img src="/images/kontact-slider.jpg" />
<div class="caption">
<p class="caption-text-3">Coffee<br>Drinks<br>Food<br>& More</p>
</div>
</div>
<div class="item fade">
<img src="/images/seminar-slider.jpg" />
<div class="caption">
<p class="caption-text-3">Seminar Rooms<br>Inspiration<br>Shopping<br>& More</p>
</div>
</div>
</div>
<!-- Next and previous buttons -->
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
</div>
<!-- The dots/circles -->
<div class="align-text-center">
<span class="dot" onclick="currentSlide(1)"></span>
<span class="dot" onclick="currentSlide(2)"></span>
<span class="dot" onclick="currentSlide(3)"></span>
<span class="dot" onclick="currentSlide(3)"></span>
</div>
How is this: http://jsfiddle.net/lharby/qox05y96/
For simplification I have stripped out the dot animation (although that code is closer to the effect you want).
Here is the simplified JS:
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("item");
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].classList.remove('active'); // this is updated
}
slides[slideIndex - 1].className += " active";
}
//automatic
var slideIndexAuto = 0;
showSlidesAuto();
function showSlidesAuto() {
var i;
var slides = document.getElementsByClassName("item");
var dots = document.getElementsByClassName("dot");
for (i = 0; i < slides.length; i++) {
slides[i].classList.remove('active'); // this is updated
}
slideIndexAuto++;
if (slideIndexAuto > slides.length) {
slideIndexAuto = 1
}
slides[slideIndexAuto - 1].classList.add('active'); // this is updated
setTimeout(showSlidesAuto, 4000);
}
This means we also have to change the css. display none/block is harder to animate with css transitions. So I have used opacity: 0/1 and visibility: hidden/visible. However one other trade off is that that the item elements cannot be positioned relatively this would stack them on top of one another (or side by side) usually for an animated slideshow you would use position absolute for each slide, but I realise that causes you another issue.
CSS:
.slider .slider-items .item {
visibility: hidden;
opacity: 0;
transition: 4s;
}
.slider .slider-items .item.active {
visibility: visible;
opacity: 1;
transition: 4s;
}
At least now all of the css is handled within the css and the js purely adds or removes a class name which I feel makes it a bit easier to update.
There are priorities as far as what CSS deems should happen.
Take a look at this and let me know if it changes anything for you. If not I'll try and run the code and fix your errors. I want to let you know in advance, I am a pure JS developer. When I need CSS or HTML I create it in JS. I want you to try first, thus it will make you a better developer.
https://www.thebookdesigner.com/2017/02/styling-priorities-css-for-ebooks-3/
I have a set of img them work as tabs and over them img of locks.
my goal is to have the lock witch is the img on top be made hidden and the tab img become clickable.
HTML
<div id="Tabs">
<img class="tablinks" id="tab_button_1" onclick="tabEvent('tab_button_1', event, 'tab1')" src="Assets/Button_Tabs_Center.png" style="width:80px;height:28px;">
<img class="tablinks" id="tab_button_2" onclick="tabEvent('tab_button_2', event, 'tab2')" src="Assets/Button_Tabs_Center.png" style="width:80px;height:28px;">
<img class="tablinks" id="tab_button_3" onclick="tabEvent('tab_button_3', event, 'tab3')" src="Assets/Button_Tabs_Center.png" style="width:80px;height:28px;">
</div>
<div id="Tabs_locks">
<img id="tab_lock_1" src="Assets/lock.png" style="position:relative;width:18px;height:28px;left:30px">
<img id="tab_lock_2" src="Assets/lock.png" style="position:relative;width:18px;height:28px;left:30px">
<img id="tab_lock_3" src="Assets/lock.png" style="position:relative;width:18px;height:28px;left:30px">
</div>
Javascript
function tabEvent(id, evt, tabName) {
var tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
}
document.getElementById("tab_lock_1").style.visibility = "hidden"
document.getElementById("tab_lock_2").style.visibility = "hidden"
document.getElementById("tab_lock_3").style.visibility = "hidden"
there is some css code that moves the imgs on top of each other with the tabs being z index 1 and the locks being z index 2.
whenever I make the lock img hidden it disappears but the tab img under it is not clickable it is clickable if the lock img is not in the code.
Key here is to add the CSS that makes the lock layer "click through" with pointer-events: none;, here let me demonstrate.
I have my functions in a namespace to make it "contained" in my "tabthing" and cache some things at the start in my tabthings object but other than that it is pretty standard.
I also dispensed with all the ID's and in-line styles and used classes as more standard when working with visual elements.
(function(tabthing, undefined) {
var tabthings = {
tabClassName: "tab-link",
tablockClassName: "tab-lock",
tabcontentClassName: "tab-content",
activeClassList: "active-show",
inactiveClassList: "inactive-hide",
tabLinks: {},
tabLocks: {},
tabContents: {},
linksParent: {},
locksParent: {},
contentParent: {}
};
function toggleclass(thisnode, isTrue = true) {
thisnode.classList.toggle(tabthings.activeClassList, isTrue);
thisnode.classList.toggle(tabthings.inactiveClassList, !isTrue);
}
function toggleActive(thisnode) {
toggleclass(thisnode, true);
}
function toggleInActive(thisnode) {
toggleclass(thisnode, false)
}
function toggleRelated(thisnode) {
let meIndex = [].indexOf.call(tabthings.linksParent.children, thisnode);
thisnode.classList.toggle("active", true);
if (thisnode.classList.contains("active")) {
toggleActive(tabthings.tabContents[meIndex]);
toggleInActive(tabthings.tabLocks[meIndex]);
} else {
inActivateAll(tabthings.tabLocks);
}
}
function inActivateAll(things) {
var i = things.length;
while (i--) {
toggleInActive(things[i]);
}
}
function activateAll(things) {
for (let i = 0; i < things.length; i++) {
toggleActive(things[i]);
}
}
function tabClickHandler(event) {
let meTab = this; //event.target;//same as this
// already active, do nothing
if (this.classList.contains('active')) {
inActivateAll(tabthings.tabContents);
toggleActive(tabthings.tabContents[0]);
meTab.classList.toggle("active", false);
return;
}
activateAll(tabthings.tabLocks);
inActivateAll(tabthings.tabContents);
for (let i = 0; i < tabthings.tabLinks.length; i++) {
tabthings.tabLinks[i].classList.toggle("active", false);
}
toggleRelated(meTab);
}
tabthing.setup = function() {
tabthings.linksParent = document.getElementById("tab-link-container");
tabthings.locksParent = document.getElementById("tab-lock-container");
tabthings.contentParent = document.getElementById("tab-content-container");
tabthings.tabLinks = document.getElementsByClassName(tabthings.tabClassName);
tabthings.tabLocks = document.getElementsByClassName(tabthings.tablockClassName);
tabthings.tabContents = document.getElementsByClassName(tabthings.tabcontentClassName);
// add event handlers
for (let i = 0; i < tabthings.tabLinks.length; i++) {
tabthings.tabLinks[i].addEventListener("click", tabClickHandler);
}
// trigger first tab click event
const clickevent = new Event('click');
tabthings.tabLinks[0].dispatchEvent(clickevent);
};
}(window.tabthing = window.tabthing || {}));
// call the setup function
tabthing.setup();
.mass-container {
border: 1px solid lime;
display: flex;
}
#tab-link-container,
#tab-lock-container {
grid-column: 1;
grid-row: 1;
}
#tab-link-container {
width: 100%;
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 1rem;
border: 1px solid red;
top: 1px;
grid-row-start: 1;
grid-row-end: 12;
}
#tab-lock-container {
width: 100%;
margin-left: -100%;
display: grid;
border: 1px solid blue;
top: 1px;
grid-row-start: 1;
grid-row-end: 1;
grid-column-start: 1;
grid-column-end: 12;
pointer-events: none;
}
#tab-content-container {
border: solid cyan 1px;
display: grid;
}
.tab-content {
grid-row-start: 1;
grid-row-end: 1;
grid-column-start: 1;
grid-column-end: 12;
}
.tab-link,
.tab-lock {
margin-left: 1rem;
margin-right: 1rem;
margin-top: 1rem;
margin-bottom: 1rem;
}
.tab-lock {
display: flex;
justify-content: flex-end;
}
.tab-lock-1 {
grid-column-start: 1;
grid-column-end: 4;
}
.tab-lock-2 {
grid-column-start: 5;
grid-column-end: 8;
}
.tab-lock-3 {
grid-column-start: 9;
grid-column-end: 12;
}
.active-show {
visibility: visible;
}
.inactive-hide {
visibility: hidden;
}
.active {
background-color: #dddddd;
}
<div class="mass-container">
<div id="tab-link-container">
<span class="tab-link tab-link-1"><img src="Assets/Button_Tabs_Center.png" alt="first-img" /></span>
<span class="tab-link tab-link-2"><img src="Assets/Button_Tabs_Center.png" alt="second-img" /></span>
<span class="tab-link tab-link-3"><img src="Assets/Button_Tabs_Center.png" alt="third-img" /></span>
</div>
<div id="tab-lock-container">
<span class="tab-lock tab-lock-1 "><img src="Assets/lock.png" alt="1lck" /></span>
<span class="tab-lock tab-lock-2"><img src="Assets/lock.png" alt="2lck" /></span>
<span class="tab-lock tab-lock-3"><img src="Assets/lock.png" alt="3lck" /></span>
</div>
</div>
<div id="tab-content-container">
<div class="tab-content"><h2>h2 is good</h2>First off this is content</div>
<div class="tab-content"><h2>tab2 cool</h2>Second we have more content</div>
<div class="tab-content"><h2>tab3 Yay</h2>Now, this is still content</div>
</div>
The tab img is not clickable because although you have hidden the lock img, it still exists on top of the tab img. It doesn't disappear. Its like keeping one layer on the other.
What you can do is, use hover property. You can change the image on hover, instead of keeping 2 images one on the other.
or you could keep the lock image clickable.
Using hover property will be a better coding practice.
Edit : Another way is using a div with the onclick event and changing the background for div on hover
<html>
<head>
<title>Change img on hover</title>
</head>
<style>
#imgDiv1{
width : 100px ;
height : 100px ;
display : block;
background: url("Assets/lock.png");
}
#imgDiv1:hover {
width : 100px;
height : 100px ;
display : block;
background: url("Assets/Button_Tabs_Center.png") ;
}
</style>
<body>
<div id="imgDiv1" onclick="tabEvent()"></div>
<!-- Add more divs as required -->
</body>
</html>
In the code below, when I click on one of the two images it opens a gallery, and if I click on the other one it should open a different gallery. It works, but not as I expected because as you can see on the snippet there are some empty slides in each gallery. Can you help me solve this problem? Thank you!
// Get the image and insert it inside the modal
function imgg(id){
var modal = document.getElementById(id);
var modalImg = document.getElementById('mySlides');
modal.style.display = "block";
modalImg.src = this.src;
}
// When the user clicks on <span> (x), close the modal
function clos(id) {
var modal = document.getElementById(id);
modal.style.display = "none";
}
// Sliseshow
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";
}
#myImg {
border-radius: 5px;
cursor: pointer;
transition: 0.3s;
}
#myImg:hover {opacity: 0.7;}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}
/* Modal Content (image) */
.mySlides {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
box-shadow: 0px 0px 50px -6px #000;
}
#-webkit-keyframes zoom {
from {-webkit-transform:scale(0)}
to {-webkit-transform:scale(1)}
}
#keyframes zoom {
from {transform:scale(0)}
to {transform:scale(1)}
}
/* The Close Button */
.close {
position: absolute;
top: 15px;
right: 100px;
color: #f1f1f1;
font-size: 40px;
font-weight: bold;
transition: 0.3s;
}
.close:hover,
.close:focus {
color: #bbb;
text-decoration: none;
cursor: pointer;
}
/* 100% Image Width on Smaller Screens */
#media only screen and (max-width: 700px){
.mySlides {
width: 100%;
}
}
.w3-btn-floating {
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="test.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
</head>
<body>
<img id="myImg" onClick="imgg('myModal')" src="http://www.gettyimages.pt/gi-resources/images/Homepage/Hero/PT/PT_hero_42_153645159.jpg" alt="" width="300" height="200">
<img id="myImg" onClick="imgg('myModal1')"src="http://cue.me/kohana/media/frontend/js/full-page-scroll/examples/imgs/bg2.jpg" alt="" width="300" height="200">
<!-- The Modal -->
<div id="myModal" class="modal">
<span onclick="clos('myModal')" class="close">×</span>
<img class="mySlides" id="img_modal" src="http://cue.me/kohana/media/frontend/js/full-page-scroll/examples/imgs/bg2.jpg" >
<img class="mySlides" id="img_modal" src="http://cdn.theatlantic.com/assets/media/img/photo/2015/11/images-from-the-2016-sony-world-pho/s01_130921474920553591/main_900.jpg" >
<a class="w3-btn-floating" style="position:absolute;top:45%;left:280px;" onclick="plusDivs(-1)">❮</a>
<a class="w3-btn-floating" style="position:absolute;top:45%;right:280px;" onclick="plusDivs(1)">❯</a>
</div>
<div id="myModal1" class="modal">
<span onclick="clos('myModal1')" class="close">×</span>
<img class="mySlides" id="img_modal" src="http://www.gettyimages.pt/gi-resources/images/Homepage/Hero/PT/PT_hero_42_153645159.jpg" >
<img class="mySlides" id="img_modal" src="http://i.dailymail.co.uk/i/pix/2016/03/22/13/32738A6E00000578-3504412-image-a-6_1458654517341.jpg" >
<a class="w3-btn-floating" style="position:absolute;top:45%;left:280px;" onclick="plusDivs(-1)">❮</a>
<a class="w3-btn-floating" style="position:absolute;top:45%;right:280px;" onclick="plusDivs(1)">❯</a>
</div>
</body>
</html>
I'm not 100% sure, but this line
var x = document.getElementsByClassName("mySlides");
should return 4 items. That would explain why you are getting 2 empty slides in your slider. Try filtering first by id (e.g. "myModal" or "myModal1") and afterwards get the number of the contained "mySlides"-classes.
so you can do it like this:
var activeModalId = "";
// Get the image and insert it inside the modal
function imgg(id){
activeModalId = id;
var modal = document.getElementById(activeModalId);
var modalImg = modal.getElementsByClassName('mySlides');
modal.style.display = "block";
showDivs(0);
}
// When the user clicks on <span> (x), close the modal
function clos() {
var modal = document.getElementById(activeModalId);
modal.style.display = "none";
activeModalId = "";
}
// Sliseshow
var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n) {
showDivs(slideIndex += n);
}
function showDivs(n) {
var i;
var x = document.getElementById(activeModalId).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";
}
On top, you declare your active modal. It will be set, reused, and removed by your functions.
From what I can see there are some url typos.
For example: you have ihttp where it should be http.
In the mouse one there's an unnecessary url termination after .jpg: ?1448476701
you need to pass "this" into function like
onClick="imgg('myModal',this)"
now in function get it
function imgg(id,this){
var modal = document.getElementById(id);
var modalImg = document.getElementById('mySlides');
modal.style.display = "block";
modalImg.src = this.src;}
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) });
}
});