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>
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'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%
i am trying to made progress bar but its can working plz solve it .
i am using if else for increasing the width but it's not working
var x = document.getElementById("p_bar");
for(var i = 0; i < 100; i++) {
var wid;
wid=1;
if(wid == 800)
break;
else
wid+=8;
x.style.width=wid+"px";
}
document.body.style.background = "#"+((1<<24)*Math.random()|0).toString(16);
#cont {
width: 800px;
height: 30px;
background-color: cornsilk;
position: relative;
}
#p_bar {
width: 8px;
height: 30px;
background-color: red;
position: absolute;
}
<div id="cont">
<div id="p_bar"></div>
</div>
<p id="write"></p>
var x=document.getElementById("p_bar");
var wid = 1;
var it = setInterval(function(){
if(wid <= 800){
wid+=8;
x.style.width=wid+"px";
}else{
clearInterval(it);
}
}, 1000);
document.body.style.background = "#"+((1<<24)*Math.random()|0).toString(16);
#cont{
width: 800px;
height: 30px;
background-color: cornsilk;
position: relative;
}
#p_bar{
width: 8px;
height: 30px;
background-color: red;
position: absolute;
}
<div id="cont">
<div id="p_bar"></div></div>
<p id="write"></p>
If you want to see moving progress bar, You should use setInterval().
If you use just for, you can't see any animation.
Because, computer's calculating is so fast, so you can see only the result of for
I wrote it again using functions, try this shubham:
var x = document.getElementById('p_bar');
var container = document.getElementById('cont');
var write = document.getElementById('write');
var containerWidth = container.offsetWidth;
var currentWidth = x.offsetWidth;
var compeleteProgress = function (step, every) {
currentWidth = Math.min(currentWidth + step, containerWidth);
write.innerHTML = Math.floor((currentWidth / containerWidth) * 100) + '%' // Priniting percentage
x.style.width = currentWidth + 'px'
if (currentWidth < containerWidth) setTimeout(function () {
compeleteProgress(step, every)
}, every)
}
compeleteProgress(8, 300) // When you call this function, everything starts
document.body.style.background = "#"+((1<<24)*Math.random()|0).toString(16);
#cont{
width: 800px;
height: 30px;
background-color: cornsilk;
position: relative;
}
#p_bar{
width: 8px;
height: 30px;
background-color: red;
position: absolute;
}
<div id="cont">
<div id="p_bar"></div>
</div>
<p id="write"></p>
I am not sure what behavior you really expects. The Bar size is usually changed according to any application events (in my example by timeouts). I hope this helps:
document.body.style.background = "#"+((1<<24)*Math.random()|0).toString(16);
var setBarWidthInPercent = function(barId, value){
var bar=document.getElementById(barId);
bar.style.width = value+"%";
}
setTimeout(function(){
setBarWidthInPercent("p_bar",10)
},500)
setTimeout(function(){
setBarWidthInPercent("p_bar",50)
},1500)
setTimeout(function(){
setBarWidthInPercent("p_bar",100)
},3000)
#cont{
width: 800px;
height: 30px;
background-color: cornsilk;
position: relative;
}
#p_bar{
width: 8px;
height: 30px;
background-color: red;
position: absolute;
-webkit-transition: width 1s ease-in-out;
-moz-transition: width 1s ease-in-out;
-o-transition: width 1s ease-in-out;
transition: width 1s ease-in-out;
}
<div id="cont">
<div id="p_bar"></div></div>
<p id="write"></p>
I would like to have the first image slide from left to right. The second image slides from left to right, and the third image will be coming from the bottom to top. I managed to slide the first image from left to right with the answers I found here on stackoverflow. But when I modified the script & css for the other images, they're not sliding. I am not so knowledgeable in javascript.
$(document).ready(function() {
function animateImgs() {
$('ul.slide1 li:not(.visible)').first().animate({
'margin-right': '500px'
}, 2000, function() {
$(this).addClass('visible');
animateImgs();
});
}
animateImgs();
});
.content {
position: relative;
margin: 0 auto;
top: 0;
left: 0;
width: 500px;
height: 500px;
border: 1px solid #000;
overflow: hidden;
}
img {
width: 100%;
height: 100%;
border-radius: 50%;
position: absolute;
}
.img1 {
max-width: 300px;
max-height: 300px;
z-index: 2;
}
.img2 {
max-width: 260px;
max-height: 260px;
z-index: 3;
left: 200px;
top: 100px;
}
.img3 {
max-width: 200px;
max-height: 200px;
z-index: 4;
left: 65px;
top: 235px;
}
/* -------------------------------------------------------------------- */
ul {
padding: 0;
margin: 0;
overflow: hidden;
}
ul.slide1 li {
float: right;
margin: 0 10px 0 0;
margin-right: 9999px;
list-style-type: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="content">
<ul class="slide1">
<li>
<img src="http://www.pngmart.com/files/4/Chrysanthemum-Transparent-Background.png" class="img1 slideLeft" />
</li>
</ul>
<img src="http://www.estanciavitoria.com/en/images/sobre_planta.png" class="img2 slideRight" />
<ul class="slide3">
<li>
<img src="https://s-media-cache-ak0.pinimg.com/originals/4d/09/e4/4d09e455070957363b2c0660a0d8cfef.png" class="img3 slideUp" />
</li>
</ul>
</div>
Steps:
Define a container element with class slideContent
Within container define slide elements with class slide
Specify sliding direction to slide elements with either slideUp, slideDown, slideLeft or slideRight
Specify data-margin to place element in container by sliding
Do not define following in CSS (instead use data-margin attribute in slide element):
margin-bottom for slideUp element
margin-top for slideDown element
margin-right for slideLeft element
margin-left for slideRight element
$(document).ready(function() {
function animateImgs() {
// Animation duration
var duration = 200;
// Get element reference needs to be shown
var el = $('.slideContent .slide:not(.visible)').first();
if (el.length === 0) {
console.log('No more elements found');
return;
}
// Read the margin value
var marginValue = el.attr('data-margin');
// Direction
var marginDirection,
animationProp = {};
// Animate now
if (el.hasClass('slideLeft')) {
marginDirection = 'margin-right';
} else if (el.hasClass('slideRight')) {
marginDirection = 'margin-left';
} else if (el.hasClass('slideUp')) {
marginDirection = 'margin-bottom'
} else if (el.hasClass('slideDown')) {
marginDirection = 'margin-top'
}
if (typeof marginDirection === 'undefined') {
// No valid animation direction defined
console.log('Invalid animation direction');
return;
}
animationProp[marginDirection] = marginValue;
el.animate(animationProp, duration, function() {
$(this).addClass('visible');
animateImgs();
});
}
animateImgs();
});
.slideContent {
position: relative;
margin: 0 auto;
top: 0;
left: 0;
width: 500px;
height: 500px;
border: 1px solid #000;
overflow: hidden;
}
.slideContent .slide {
position: absolute;
}
.slideContent .slideLeft {
right: -100%
}
.slideContent .slideRight {
left: -100%
}
.slideContent .slideUp {
bottom: -100%
}
img {
width: 100%;
height: 100%;
border-radius: 50%;
}
.img1 {
max-width: 300px;
max-height: 300px;
}
.img2 {
max-width: 260px;
max-height: 260px;
top: 100px;
}
.img3 {
max-width: 200px;
max-height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="slideContent">
<img src="http://www.pngmart.com/files/4/Chrysanthemum-Transparent-Background.png" data-margin="500px" class="img1 slide slideLeft" />
<img src="http://www.estanciavitoria.com/en/images/sobre_planta.png" data-margin="600px" class="img2 slide slideRight" />
<img src="https://s-media-cache-ak0.pinimg.com/originals/4d/09/e4/4d09e455070957363b2c0660a0d8cfef.png" data-margin="600px" class="img3 slide slideUp" />
</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.