I'm working with an image fader program, but I'm not understanding absolute positioning. I have the images fading nicely and resizing the way I want if the screen resizes. but I have 2 problems. Div#2 gets covered up by the images. I want div2 to always appear below the image div. Also, I have control buttons on the images. I want them in the middle. I thought using top:50% would do that, but it's not. Here's an example...
var slides = document.querySelectorAll('#slides .slide');
var currentSlide = 0;
var slideInterval = setInterval(nextSlide,5000);
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';}
var next = document.getElementById('next');
var previous = document.getElementById('previous');
next.onclick = function(){nextSlide();};
previous.onclick = function(){previousSlide();};
#slides {position: relative}
.slide{
position: absolute;
left: 0px;
top: 0px;
width:100%;
height:auto;
min-height:300px;
object-fit:cover;
opacity: 0;
box-sizing:border-box;
transition: opacity 2s;}
.showing{opacity: 1;}
.controls{
background: transparent;
color: #fff;
font-size: 30px;
cursor: pointer;
border: 1px solid #555;
width: 30px;
position: absolute;
}
.controls:hover{ opacity:.5}
.fadenext{right: 10px; top: 50%;}
.fadeprev{left: 10px; top: 50%;}
<br><br>
<div id="slides">
<img src='https://www.panotools.org/dersch/Monp.JPG' class="slide showing">
<img src='https://www.panotools.org/dersch/StBp.JPG' class="slide">
<button class="controls fadeprev" id="previous"><</button>
<button class="controls fadenext" id="next">></button>
</div>
<div style='margin-top:40px;border:1px solid red;width:200px;height:100px'>
This is Div # 2</div>
I've amended your snippet to fix your issues.
Adding margin-top instead of top will fix your issue with the
controls.
Div 2 will now always remain below your slider.
P.S. I moved your div2 inline styles to keep it neat.
var slides = document.querySelectorAll('#slides .slide');
var currentSlide = 0;
var slideInterval = setInterval(nextSlide, 5000);
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';
}
var next = document.getElementById('next');
var previous = document.getElementById('previous');
next.onclick = function() {
nextSlide();
};
previous.onclick = function() {
previousSlide();
};
* {
margin: 0;
padding: 0;
}
#slides {
position: relative
}
.slide {
position: absolute;
left: 0px;
top: 0px;
width: 100%;
height: auto;
min-height: 300px;
object-fit: cover;
opacity: 0;
box-sizing: border-box;
transition: opacity 2s;
}
.showing {
opacity: 1;
}
.controls {
background: transparent;
color: #fff;
font-size: 30px;
cursor: pointer;
border: 1px solid #555;
width: 30px;
position: absolute;
}
.controls:hover {
opacity: .5
}
.fadenext {
right: 10px;
margin-top: 25%;
}
.fadeprev {
left: 10px;
margin-top: 25%;
}
.div2 {
margin-top: 50%;
border: 1px solid red;
width: 200px;
height: 100px;
}
<br><br>
<div id="slides">
<img src='https://www.panotools.org/dersch/Monp.JPG' class="slide showing">
<img src='https://www.panotools.org/dersch/StBp.JPG' class="slide">
<button class="controls fadeprev" id="previous"><</button>
<button class="controls fadenext" id="next">></button>
</div>
<div class="div2">This is Div # 2</div>
It's not feasible to use % based positions when you use "top" style. So to achieve what you want to do, use margin-top instead. As shown below:
.fadenext{right: 10px; margin-top: 25%;}
.fadeprev{left: 10px; margin-top: 25%;}
And for your div2, just change it's style to:
margin-top: 50%
Related
I created a slideshow with 3 slides but for some reason, it keeps adding an additional slide
const slideshow = document.getElementById("slideshow");
const slides = slideshow.children;
let currentSlide = 0;
function goToSlide(n) {
slides[currentSlide].classList.remove("active");
currentSlide = (n + slides.length) % slides.length;
slides[currentSlide].classList.add("active");
updateSlideshowCounter();
}
function nextSlide() {
goToSlide(currentSlide + 1);
}
function prevSlide() {
goToSlide(currentSlide - 1);
}
function updateSlideshowCounter() {
const slideshowCounter = document.getElementById("slideshow-counter");
slideshowCounter.textContent = `${currentSlide + 1} / ${slides.length}`;
}
const prevButton = document.getElementById("prev-button");
prevButton.addEventListener("click", prevSlide);
const nextButton = document.getElementById("next-button");
nextButton.addEventListener("click", nextSlide);
updateSlideshowCounter();
#slideshow {
position: relative;
text-align: center;
width: 400px;
height: 300px;
border: 1px black solid;
}
.slide {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 1s;
}
.slide.active {
opacity: 1;
}
#slideshow-controls {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
align-items: center;
}
#prev-button,
#next-button {
padding: 10px 20px;
border: none;
background-color: #333;
color: #fff;
cursor: pointer;
}
#prev-button {
margin-right: 20px;
}
#next-button {
margin-left: 20px;
}
#slideshow-counter {
margin: 0 20px;
}
<div id="slideshow">
<div class="slide">Slide 1</div>
<div class="slide">Slide 2</div>
<div class="slide">Slide 3</div>
<div id="slideshow-controls">
<button id="prev-button">Prev</button>
<span id="slideshow-counter"></span>
<button id="next-button">Next</button>
</div>
</div>
Can someone tell me what my mistake is and how I can get 3 slides in the output instead of 4.
You're defining your slides with the statement const slides = slideshow.children;. Your slideshow has a total of 4 direct children, so the counter is technically correct (see slide 1, slide 2, slide 3, and slideshow-controls).
One approach to get just the slides you want is to use const slides = document.getElementsByClassName("slide"). I hope this helps!
The problem is your slides variable is not assigned to the correct list of elements, as the previous answer said, you should replace slideshow.children with either document.getElementsByClassName('slide') or document.querySelectorAll('.slide'), use any of the two.
By using slideshow.children, you're not getting .slide classes, you're getting all children of #slideshow.
So, your variable in line 67, should be as the following:
const slides = document.querySelectorAll('.slide');
or
const slides = document.getElementsByClassName('.slide');
You should keep slideshow controls out of your slideshow div. I am attaching Code Below. Run it and check.
const slideshow = document.getElementById("slideshow");
const slides = slideshow.children;
let currentSlide = 0;
function goToSlide(n) {
slides[currentSlide].classList.remove("active");
currentSlide = (n + slides.length) % slides.length;
slides[currentSlide].classList.add("active");
updateSlideshowCounter();
}
function nextSlide() {
goToSlide(currentSlide + 1);
}
function prevSlide() {
goToSlide(currentSlide - 1);
}
function updateSlideshowCounter() {
const slideshowCounter = document.getElementById("slideshow-counter");
slideshowCounter.textContent = `${currentSlide + 1} / ${slides.length}`;
}
const prevButton = document.getElementById("prev-button");
prevButton.addEventListener("click", prevSlide);
const nextButton = document.getElementById("next-button");
nextButton.addEventListener("click", nextSlide);
updateSlideshowCounter();
#slideshowbox {
position: relative;
width: 400px;
height: 300px;
}
#slideshow {
position: relative;
text-align: center;
width: 400px;
height: 300px;
border: 1px black solid;
}
.slide {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 1s;
}
.slide.active {
opacity: 1;
}
#slideshow-controls {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
align-items: center;
}
#prev-button,
#next-button {
padding: 10px 20px;
border: none;
background-color: #333;
color: #fff;
cursor: pointer;
}
#prev-button {
margin-right: 20px;
}
#next-button {
margin-left: 20px;
}
#slideshow-counter {
margin: 0 20px;
}
<div id="slideshowbox">
<div id="slideshow">
<div class="slide">Slide 1</div>
<div class="slide">Slide 2</div>
<div class="slide">Slide 3</div>
</div>
<div id="slideshow-controls">
<button id="prev-button">Prev</button>
<span id="slideshow-counter"></span>
<button id="next-button">Next</button>
</div>
</div>
Your slideshow div childs is throwing 4 because your 4th div is slideshow-controls. You may want to add -1 to the counter or redifine the way you make your div. Best of luck!
I have created an image slider with many images using some javascript and css. I just used client width to get the size of the image (which vary slightly) and calculated the translateX distance with a counter variable. Added a css transition in the end. However I can't seem to get the slider to translate the whole image correctly. I don't know why it's going wrong. I have used 'vw' in the calculations for responsiveness. I am new to javascript and would love any tips for other parts for other parts of code as well.
here is the JS fiddle link- https://jsfiddle.net/n6smpv2j/15/
HTML
<div id="lookbook" data-tab-content class="black-text">
<div class="lookbook-nav">
<button id="left">←</button>
<button id="right">→</button>
</div>
<div class="lookbook">
<div class="slider">
<img src="https://loremflickr.com/640/360" id="lastClone" alt="">
<img src="https://picsum.photos/640/400">
<img src="https://loremflickr.com/640/360">
<img src="https://picsum.photos/640/400">
<img src="https://loremflickr.com/640/360">
<img src="https://picsum.photos/640/400">
<img src="https://loremflickr.com/640/360">
<img src="https://picsum.photos/600/400">
<img src="https://fillmurray.com/600/330">
<img src="https://picsum.photos/600/400">
<img src="https://fillmurray.com/600/330">
<img src="https://picsum.photos/600/400">
<img src="https://loremflickr.com/640/360">
<img src="https://picsum.photos/600/400">
<img src="https://loremflickr.com/640/360">
<img src="https://picsum.photos/600/400" id="firstClone" alt="">
</div>
</div>
</div>
JS
const slider = document.querySelector('.slider');
const sliderImages = document.querySelectorAll('.slider img');
const leftbtn = document.querySelector('#left');
const rightbtn = document.querySelector('#right');
let counter = 1;
const size = sliderImages[0].clientWidth;
slider.style.transform = 'translateX(' + (-size * counter) + 'vw)';
rightbtn.addEventListener('click', () => {
if (counter >= sliderImages.length - 1) return;
slider.style.transition = "transform 0.4s ease-in";
counter++;
slider.style.transform = 'translateX(' + (-size * counter) + 'vw)'
})
leftbtn.addEventListener('click', () => {
if (counter <= 0) return;
slider.style.transition = "transform 0.4s ease-in";
counter--;
slider.style.transform = 'translateX(' + (-size * counter) + 'vw)'
})
slider.addEventListener('transitionend', () => {
if (sliderImages[counter].id === "lastClone") {
slider.style.transition = "none";
counter = sliderImages.length - 2;
slider.style.transform = 'translateX(' + (-size * counter) + 'vw)'
}
if (sliderImages[counter].id === "firstClone") {
slider.style.transition = "none";
counter = sliderImages.length - counter;
slider.style.transform = 'translateX(' + (-size * counter) + 'vw)'
}
})
CSS
#lookbook {
width: 100vw;
height: 100vh;
}
.lookbook-nav {
width: 70vw;
height: 10vh;
margin-left: 15vw;
margin-top: 45vh;
position: absolute;
display: flex;
justify-content: space-between;
align-items: center;
}
button {
border: none;
outline: none;
background: transparent;
font-size: 2rem;
/* font-weight: bold; */
cursor: pointer;
}
.lookbook-nav button {
border: none;
outline: none;
background: transparent;
font-size: 2rem;
/* font-weight: bold; */
cursor: pointer;
}
button:hover {
opacity: 0.4;
}
.lookbook {
width: 56vw;
height: 91vh;
margin: auto;
overflow: hidden;
}
.lookbook img {
width: 100%;
height: auto !important;
}
.slider {
margin-top: 10vh;
display: flex;
width: auto;
}
The answer from #DecjazMach solves the most important problem but doesn't cover everything. For example, the solution also still uses the width of the first image to set the width of the visible slider. This will be fine in many cases, but what if the first image is a skinny tall portrait and the rest landscape or vice versa?
#Laiqa Mohid also welcomed any other suggestions so here are some which come out of trying to simplify things, for example minimising the calculation needed in the JS and the 'work' the system has to do on a click.
You can try it here http://bayeuxtapestry.rgspaces.org.uk/slider
Notes:
The size of the visible portion of the slider is not dependent on the dimensions of the first image
imgs have been replaced with divs + background-image so that different sizes/aspect ratios can be accommodated without any need for javascript calculation - this automatically helps responsiveness
these divs are all of the same dimensions so the amount the slider needs to move does not depend on the size of the image
images that do not fill the whole width (because they are too tall relatively) will be centred
images are also centred vertically. This can be changed if required (e.g. to align to the top of the slider) by changing the background-position in .slider div
Using a transform:translateX works but requires a calculation in the Javascript. We can use CSS animation instead and need only move the currently visible slide and the one that is to be shown next.
The image serving services sometimes did not serve an image so I have used my own - deliberately of different sizes and aspect ratios (including portrait)
Using this method it is possible to have a continuous slider - showing the first slide if the user clicks past the last one.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>Slider</title>
<meta charset="utf-8">
<style>
#lookbook {
width: 100vw;
height: 100vh;
margin:0;
padding:0;
overflow:hidden;
}
.lookbook-nav {
width: 70vw;
height: 10vh;
margin-left: 15vw;
margin-top: 45vh;
position: absolute;
display: flex;
justify-content: space-between;
align-items: center;
}
button {
border: none;
outline: none;
background: transparent;
font-size: 2rem;
/* font-weight: bold; */
cursor: pointer;
}
.lookbook-nav button {
border: none;
outline: none;
background: transparent;
font-size: 2rem;
/* font-weight: bold; */
cursor: pointer;
}
button:hover {
opacity: 0.4;
}
div .lookbook {
width: 56vw;
}
.lookbook {
height: 91vh;
margin: auto;
overflow: hidden;
}
div.slider{
margin:0;
margin-top: 10vh;
height:81vh;/* this is height of (lookbook - margin-top) - probably better done through flex */
position:relative;
top:0;
padding:0;
width:100%;
}
#keyframes slideouttoleft {
from {
left: 0;
visibility:visible;
}
to {
left: -100%;
visibility:hidden;
}
}
#keyframes slideinfromright {
from {
left: 100%;
visibility:visible;
}
to {
left: 0;
visibility:visible;
}
}
#keyframes slideouttoright {
from {
left: 0;
visibility:visible;
}
to {
left: 100%;
visibility:hidden;
}
}
#keyframes slideinfromleft {
from {
left: -100%;
visibility:visible;
}
to {
left: 0;
visibility:visible;
}
}
.slider div {
position:absolute;
top:0;
left:0;
overflow:hidden;
visibility:hidden;
margin: 0;
padding: 0;
width:100%;
height:100%;
background-size: contain;
background-position: center center;
background-repeat: no-repeat no-repeat;
animation-duration: 0.4s;
animation-delay: 0s;
animation-iteration-count: 1;
animation-direction: normal;
animation-timing-function: ease-in;
animation-fill-mode: forwards;
}
</style>
</head>
<body>
<div id="lookbook" data-tab-content class="black-text">
<div class="lookbook-nav">
<button id="left">←</button>
<button id="right">→</button>
</div>
<div class="lookbook">
<div class="slider">
<!-- images taken from Reading (UK) Museum's Victorian copy of the Bayeux Tapestry -->
<div style="background-image:url(https://rgspaces.org.uk/bayeuxtapestry/wp-content/uploads/boat-and-horses-768x546.png);"></div>
<div style="background-image:url(https://rgspaces.org.uk/bayeuxtapestry/wp-content/uploads/two-horses-300x212.png);"></div>
<div style="background-image:url(https://rgspaces.org.uk/bayeuxtapestry/wp-content/uploads/woman-and-child-1200x901.png);"></div>
<div style="background-image:url(https://rgspaces.org.uk/bayeuxtapestry/wp-content/uploads/archer-2-768x1100.png);"></div>
<div style="background-image:url(https://rgspaces.org.uk/bayeuxtapestry/wp-content/uploads/boat-builder-2-878x1024.png);"></div>
<div style="background-image:url(https://rgspaces.org.uk/bayeuxtapestry/wp-content/uploads/group-1-768x603.png);"></div>
<div style="background-image:url(https://rgspaces.org.uk/bayeuxtapestry/wp-content/uploads/pointing-horseman-768x853.png);"></div>
<div style="background-image:url(https://rgspaces.org.uk/bayeuxtapestry/wp-content/uploads/group-2-768x619.png);"></div>
<div style="background-image:url(https://rgspaces.org.uk/bayeuxtapestry/wp-content/uploads/carrying-casket-768x556.png);"></div>
</div>
</div>
</div>
<script>
const slider = document.querySelector('.slider');
const sliderImages = document.querySelectorAll('.slider div');
const leftbtn = document.querySelector('#left');
const rightbtn = document.querySelector('#right');
const numImgs=sliderImages.length;
let curImg = 0;
rightbtn.addEventListener('click', () => {
sliderImages[curImg].style.animationName='slideouttoleft';
curImg=(curImg+1)%numImgs;
sliderImages[curImg].style.animationName='slideinfromright';
})
leftbtn.addEventListener('click', () => {
sliderImages[curImg].style.animationName='slideouttoright';
curImg=curImg==0? numImgs-1 : Math.abs((curImg-1)%numImgs);
sliderImages[curImg].style.animationName='slideinfromleft';
})
function initialize() {
sliderImages[0].style.animationName='slideinfromright';
}
window.onload=initialize;
</script>
</body>
</html>
That is because the size is being calculated in pixels as you can see here. So to get the width in vw you can use the following function as
const size = vw(sliderImages[0].clientWidth);
function vw(v) {
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
return (v * w) / 100;
}
For some reason, the images loaded from that source didn't work so I downloaded them locally and they did work and I've done some modification to your CSS as well.
var slider = document.getElementById("slider");
var slides = slider.childElementCount;
var i = 0;
document.getElementById("right").addEventListener("click", function () {
i == slides - 1 ? (i = 0) : i++;
slider.style.transform = "translate(-" + 600 * i + "px)";
});
body {
background-color: aqua;
}
#lookbook {
position: relative;
box-sizing: content-box;
height: auto;
max-width: 600px;
margin: auto;
}
.lookbook-nav {
position: absolute;
display: flex;
justify-content: space-between;
width: 100%;
height: 100%;
}
button {
border: none;
outline: none;
background: transparent;
font-size: 2rem;
cursor: pointer;
}
.lookbook-nav button {
border: none;
outline: none;
background: transparent;
font-size: 2rem;
/* font-weight: bold; */
cursor: pointer;
color: beige;
z-index: 2;
}
button:hover {
opacity: 0.4;
}
.lookbook {
width: auto;
height: 91vh;
margin: auto;
overflow: hidden;
}
.lookbook img {
width: 600px;
height: auto !important;
}
.slider {
margin-top: 10vh;
display: flex;
/* align-items: flex-end; */
width: auto;
/* height: 700px; */
transition: 0.5s ease-in-out;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Slider</title>
</head>
<body>
<div id="lookbook" data-tab-content class="black-text">
<div class="lookbook-nav">
<button id="left">←</button>
<button id="right">→</button>
</div>
<div class="lookbook">
<div class="slider" id="slider">
<img src="https://picsum.photos/600/360" alt="" />
<img src="https://picsum.photos/600/360" alt="" />
<img src="https://picsum.photos/600/360" alt="" />
<img src="https://picsum.photos/600/360" alt="" />
<img src="https://picsum.photos/600/360" alt="" />
<img src="https://picsum.photos/600/360" alt="" />
</div>
</div>
</div>
</body>
</html>
I just made one navigation arrow work but should be the same thing just in reverse order also you don't have to worry about the counter as it will detect how many images you have inside the slider.
I'm having a hard time figuring out why the code below doesn't work as expected.
What I'm trying to achieve is same functionality with position:sticky whereas when the scrolled reaches the top of the #second-header then fixes its position below the #header which is also fixed, however, the height of the #header is unknown which is I believe can be calculated using the function outerHeight(true) on JQuery.
Then after reaching out to the bottom of the #second-header-container, remove the fixed position of #second-header turning it back to normal position.
Due to browser compatibility issues and other customization, I cannot simply use the position:sticky of css.
It looks like my logic is wrong, and I need help.
jQuery(document).ready(function(){
var $document = jQuery(document);
var header = jQuery('#header');
var second_header = jQuery('#second-header-container').find('#second-header');
var second_header_container = jQuery('#second-header-container');
var second_header_offset = second_header.offset().top;
var second_header_container_offset = second_header_container.offset().top;
jQuery(window).scroll(function(){
var top_margin = header.outerHeight(true);
var second_header_height = second_header.outerHeight(true);
var second_header_container_height = second_header_container.outerHeight(true);
if( jQuery(window).scrollTop() > (second_header_offset - second_header_height) && jQuery(window).scrollTop() < second_header_container_height) {
second_header.addClass('fixer');
second_header.css({position:'fixed', top:top_margin, 'z-index':'999999'});
} else {
second_header.removeClass('fixer');
second_header.css({position:'relative', top:'0px', 'z-index':'0'});
}
});
});
*{
color: #FFFFFF;
padding: 0;
margin: 0;
}
.fixer{
position: fixed;
width: 100%;
}
#header, .banner, #second-header, .contents{
padding: 5px;
}
#header{
position: fixed;
width: 100%;
height: 74px;
z-index: 99999;
background-color: #000000;
}
.banner{
padding-top: 84px;
height: 200px;
background-color: #583E5B;
}
#second-header-container{
min-height: 300px;
background-color: #775F5E;
}
#second-header{
padding-bottom: 10px;
padding-top: 10px;
background-color: #4C3D3C;
}
.contents{
min-height: 200px;
background-color: #97A36D;
}
.footer{
background-color: #80A379;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header id="header">HEADER</header>
<div class="banner">BANNER</div>
<div id="second-header-container">
<div id="second-header">SECOND-HEADER</div>
<!--Other contents and elements...-->
</div>
<div class="contents">OTHER...</div>
<footer class="contents footer">FOOTER</footer>
To achieve this you need first check if the scroll height is near the second div header and within the height of the second div. Then add a class that make it stick below the main header. I have created a sticky class and added it while scrolling conditions are met.
Please check below code
jQuery(document).ready(function() {
var headerHeight = $('#header').outerHeight(true);
var secondHeaderContainer = $('#second-header-container');
const secondHeaderTopPos = secondHeaderContainer.offset().top;
const secondHeaderContainerHeight = $(secondHeaderContainer).height();
$(window).scroll(function() {
const scrollTop = $(this).scrollTop();
const secondContainerHeightEnd = secondHeaderContainerHeight + secondHeaderTopPos - $('#second-header').height() - headerHeight;
if (((secondHeaderTopPos - headerHeight) <= scrollTop) && (secondContainerHeightEnd >= scrollTop)) {
$('#second-header').addClass('sticky').css('top', headerHeight);
} else {
$('#second-header').removeClass('sticky');
}
});
});
* {
color: #FFFFFF;
padding: 0;
margin: 0;
}
.sticky {
position: fixed;
width: 100%;
top: 0;
left: 0;
}
.fixer {
position: fixed;
width: 100%;
}
#header,
.banner,
#second-header,
.contents {
padding: 5px;
}
#header {
position: fixed;
width: 100%;
height: 74px;
z-index: 99999;
background-color: #000000;
}
.banner {
padding-top: 84px;
height: 200px;
background-color: #583E5B;
}
#second-header-container {
min-height: 300px;
background-color: #775F5E;
}
#second-header {
padding-bottom: 10px;
padding-top: 10px;
background-color: #4C3D3C;
}
.contents {
min-height: 200px;
background-color: #97A36D;
}
.footer {
background-color: #80A379;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header id="header">HEADER</header>
<div class="banner">BANNER</div>
<div id="second-header-container">
<div id="second-header">SECOND-HEADER</div>
<!--Other contents and elements...-->
</div>
<div class="contents">OTHER...</div>
<footer class="contents footer">FOOTER</footer>
Against all reason, I'm trying to create a vanilla JavaScript carousel.
I am having two problems:
1. The images move left at widths of -680px as they should but when I tried to create the same function for the right button, the left value goes to 1370px making the picture off the screen.
2. I would like for it to slide left rather jump left (same for right), I managed to get it to do this but it doesn't work on the first slide, only from the second slide.
Here is the HTML code just for the carousel:
<div id = "container">
<div id = "carousel">
<div class = "slide"><img class = "slideImage" class = "active" src = "sithCover.png"></div>
<div class = "slide"><img class = "slideImage" src = "darthVader.png"></div>
<div class = "slide"><img class = "slideImage" src = "darthSidious.png"></div>
<div class = "slide"><img class = "slideImage" src = "kyloRen.png"></div>
</div>
</div>
<div id = "left" class = "button"></div>
<div id = "right" class = "button"></div>
Here is the CSS code:
#container {
position: absolute;
top: 200px;
left: 100px;
width: 680px;
height: 360px;
white-space: nowrap;
overflow:hidden;
}
#carousel {
position: absolute;
width: 2740px;
height: 360px;
white-space: nowrap;
overflow: hidden;
transition: left 300ms linear;
}
.slide {
display: inline-block;
height: 360px;
width: 680px;
padding: 0;
margin: 0;
transition: left 300ms linear;
}
.slideImage {
position:relative;
height: 360px;
width: 680px;
float: left;
}
.button {
position: absolute;
top: 340px;
height: 60px;
width: 60px;
border-bottom: 12px solid red;
}
#left {
left: 115px;
border-left: 12px solid red;
transform: rotate(45deg);
}
#right {
left: 693px;
border-right: 12px solid red;
transform: rotate(-45deg);
}
Here is the JavaScript:
var carousel = document.querySelector('#carousel');
var firstVal = 0;
document.querySelector('#left').addEventListener("click", moveLeft);
function moveLeft (){
firstVal +=685;
carousel.style.left = "-"+firstVal+"px";
};
document.querySelector('#right').addEventListener("click", moveRight);
function moveRight() {
firstVal +=685;
carousel.style.left = "+"+firstVal+"px";
};
Here is a JSFiddle so that you can see what I mean:
"https://jsfiddle.net/way81/8to1kkyj/"
I appreciate your time in reading my question and any help would be much appreciated.
Ofcourse it goes from -685px on left click and then to +1370pxthe next right click; You are always adding 685 to your firstVal variable.
firstVal = 0
//firstVal is worth 0
moveLeft()
//firstVal is now worth 685
moveRight()
//firstVal is now worth 1370.
The problem is that when you apply the firstVal to your CSS thing in the javascript, you create a string to get your negative value (where you apply the "-" sign infront of firstVal)
Instead, write them like this
function moveLeft (){
firstVal -=685; //note we now subtract, the "-" should appear when the number becomes negative
carousel.style.left = firstVal + "px";
};
function moveRight() {
firstVal +=685;
carousel.style.left = firstVal + "px";
};
var left = document.getElementById("left");
left.addEventListener("click", moveLeft, false);
var right = document.getElementById("right");
right.addEventListener("click", moveRight, false);
var carousel = document.getElementById("carousel");
var images = document.getElementsByTagName("img");
var position = 0;
var interval = 685;
var minPos = ("-" + interval) * images.length;
var maxPos = interval * images.length;
//slide image to the left side <--
function moveRight() {
if (position > (minPos + interval)) {
position -= interval;
carousel.style.left = position + "px";
}
if (position === (minPos + interval)) {
right.style.display = "none";
}
left.style.display = "block";
}
//slide image to the right side -->
function moveLeft() {
if (position < (maxPos - interval) && position < 0) {
position += interval;
carousel.style.left = position + "px";
}
if (position === 0) {
left.style.display = "none";
}
right.style.display = "block";
}
#container {
position: absolute;
top: 200px;
left: 100px;
width: 680px;
height: 360px;
white-space: nowrap;
overflow: hidden;
}
#carousel {
position: absolute;
width: 2740px;
height: 360px;
white-space: nowrap;
overflow: hidden;
transition: left 300ms linear;
}
.slide {
display: inline-block;
height: 360px;
width: 680px;
padding: 0;
margin: 0;
transition: left 300ms linear;
}
.slideImage {
position: relative;
height: 360px;
width: 680px;
float: left;
}
.button {
position: absolute;
top: 340px;
height: 60px;
width: 60px;
border-bottom: 12px solid red;
}
#left {
left: 115px;
border-left: 12px solid red;
transform: rotate(45deg);
display: none;
}
#right {
left: 693px;
border-right: 12px solid red;
transform: rotate(-45deg);
}
<div id="container">
<div id="carousel">
<div class="slide">
<img class="slideImage" class="active" src="sithCover.png" alt="slide1">
</div>
<div class="slide">
<img class="slideImage" src="darthVader.png" alt="slide2">
</div>
<div class="slide">
<img class="slideImage" src="darthSidious.png" alt="slide3">
</div>
<div class="slide">
<img class="slideImage" src="kyloRen.png" alt="slide4">
</div>
</div>
</div>
<div id="left" class="button"></div>
<div id="right" class="button"></div>
I have created a lightbox in javascript and I have placed inside it a progress bar that I have also created it in javascript. My problem is that when I was trying to insert a second progress bar inside my lightbox only the first works. Any idea how to fix this?
this is my jsfiddle :http://jsfiddle.net/QHMKk/3/
and my code is this:
my javascript is:
function show() {
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
}
function start() {
var stepSize = 50;
setTimeout((function() {
var filler = document.getElementById("filler"),
percentage = 0;
return function progress() {
filler.style.height = percentage + "%";
percentage +=1;
if (percentage <= 100) {
setTimeout(progress, stepSize);
}
}
}()), stepSize);
}
function start() {
var stepSize = 50;
setTimeout((function() {
var filler2 = document.getElementById("filler2"),
percentage = 0;
return function progress() {
filler.style.height = percentage + "%";
percentage +=1;
if (percentage <= 100) {
setTimeout(progress, stepSize);
}
}
}()), stepSize);
}
this is my html:
OPEN
<div id="light" class="white_content_stats">
<div class="prog">
<div id="filler" class="filler"></div>
</div>
</br>
<div class="prog2">
<div id="filler2" class="filler2"></div>
</div>
<a href = "javascript:void(0)" onclick = " document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'; ">
</br>CLOSE</a>
and this is my CSS:
.black_overlay_stats{
display: none;
position: absolute;
top: 0%;
left: 0%;
width: 100%;
height: 50%;
z-index:1001;
-moz-opacity: 0.6;
opacity:.70;
filter: alpha(opacity=70);
}
.white_content_stats {
display: none;
position:fixed;
top: 15%;
width: 300px;
padding: 30px;
margin-left:10px;
background-color:#F2F2F2;
border-radius: 0px;
box-shadow: 0px 0px 0px 20px rgba(0,0,0,0.6);
z-index:1002;
}
.prog {
height: 100px;
width: 30px;
border: 1px solid white;
position: relative;
}
.filler {
height: 0%;
width: 30px;
position: absolute;
bottom: 0;
background-color: grey;
}
.prog2 {
height: 100px;
width: 30px;
border: 1px solid white;
position: relative;
}
.filler2 {
height: 0%;
width: 30px;
position: absolute;
bottom: 0;
background-color: grey;
}
You define 2 functions with the same name start, so the second will be used and only it will be run, hence you can see only 1 progress bar works. You can modify the function start to make it accept an argument of id like this:
function start(id) {
//...
var filler = document.getElementById(id)
//...
}
Then call both start('filler') and start('filler2'):
OPEN
Updated Demo.
Note that you should not use inline event property.