I'm trying to make a carousel and I'm kind of stuck on stopping it from scrolling when the last slide is reached.
So far I have this JS code
var width = 130; //width of one slide
var position = 0;
var carousel = document.getElementById('carousel');
var list = carousel.querySelector('ul');
carousel.querySelector('.prev').onclick = function() {
position = Math.min(position + width, 0)
console.log(position)
list.style.marginLeft = position + 'px';
};
carousel.querySelector('.next').onclick = function() {
position = position - width
console.log(position)
list.style.marginLeft = position + 'px';
};
So I'm taking width of one slide and based on that change margin of container.
When scrolling left I solved the problem by setting position to 0 with Math.min.This way when I 'm on the first slide it doesn`t scroll left.
But I'm not sure how to do the same when on my last slide.
Link to working exmaple
Here's what you want , I just added a test comparing the position and the size of all the sliders.
var width = 130;
var carousel = document.getElementById('carousel');
var list = carousel.querySelector('ul');
var position = 0;
var carouselwidth = document.getElementsByClassName('gallery')[0].offsetWidth;
//number of silder
var nbslider = list.getElementsByTagName("li").length;
//number of silder per page
var nbsliderp = carouselwidth / width
console.log(nbsliderp);
//size of silders per page
var szsliderp = nbsliderp * width;
carousel.querySelector('.prev').onclick = function() {
position = Math.min(position + width, 0)
console.log(position)
list.style.marginLeft = position + 'px';
};
carousel.querySelector('.next').onclick = function() {
//console.log((position - szsliderp) + (nbslider * width))
if (((position - szsliderp) + (nbslider * width)) > 0) {
position = position - width
//console.log(position)
list.style.marginLeft = position + 'px';
}
};
body {
padding: 10px;
}
.carousel {
position: relative;
width: 398px;
padding: 10px 40px;
background: #eee;
}
.carousel img {
width: 130px;
height: 130px;
margin-right: 2px;
display: block;
}
.arrow {
position: absolute;
top: 60px;
padding: 0;
font-size: 24px;
line-height: 24px;
color: #444;
display: block;
}
.arrow:focus {
outline: none;
}
.arrow:hover {
background: #ccc;
cursor: pointer;
}
.prev {
left: 7px;
}
.next {
right: 7px;
}
.gallery {
width: 390px;
overflow: hidden;
}
.gallery ul {
height: 130px;
width: 9999px;
margin: 0;
padding: 0;
list-style: none;
transition: margin-left 250ms;
font-size: 0;
}
.gallery li {
display: inline-block;
}
<div id="carousel" class="carousel">
<button class="arrow prev"></button>
<div class="gallery">
<ul class="images">
<li><img src="https://cdn.houseplans.com/product/o2d2ui14afb1sov3cnslpummre/w1024.jpg?v=15"></li>
<li><img src="https://cdn.houseplans.com/product/o2d2ui14afb1sov3cnslpummre/w1024.jpg?v=15"></li>
<li><img src="https://cdn.houseplans.com/product/o2d2ui14afb1sov3cnslpummre/w1024.jpg?v=15"></li>
<li><img src="https://cdn.houseplans.com/product/o2d2ui14afb1sov3cnslpummre/w1024.jpg?v=15"></li>
<li><img src="https://cdn.houseplans.com/product/o2d2ui14afb1sov3cnslpummre/w1024.jpg?v=15"></li>
<li><img src="https://cdn.houseplans.com/product/o2d2ui14afb1sov3cnslpummre/w1024.jpg?v=15"></li>
</ul>
</div>
<button class="arrow next">></button>
</div>
Related
I have a problem with my code, I'm trying to make my menu that contains list of items scrollable on button click (left and right buttons). The thing is after i click on right button, it works but it does not let me click it again....if i do it does nothing.So it goes once right and once left only. I want to be able to keep pressing it untill i reach the last item in the menu and vice versa.
My html code for the menu:
<div class="menu-wrapper">
<ul class="menu">
<li class="item active">Hair</li>
<li class="item">Massage</li>
<li class="item">Nails</li>
<li class="item">Facial</li>
<li class="item">Tattoo</li>
<li class="item">Institue</li>
<li class="item">Masking</li>
<li class="item">Doudou</li>
<li class="item">Facial</li>
<li class="item">Tattoo</li>
<li class="item">Institue</li>
<li class="item">Masking</li>
<li class="item">Doudou</li>
</ul>
<div class="paddles">
<button class="left-paddle paddle hidden">
<
</button>
<button class="right-paddle paddle">
>
</button>
</div>
</div>
My Css code is:
.menu-wrapper {
position: relative;
border-radius: 10px;
height: 50px;
margin: 1em auto;
overflow-x: hidden;
overflow-y: hidden;
}
.menu {
height: 50px;
background: white;
box-sizing: border-box;
padding-left: 0;
white-space: nowrap;
overflow-x: hidden;
overflow-y: hidden;
-webkit-overflow-scrolling: touch;
}
.item {
display: inline-block;
width: 155px;
height: auto;
text-align: center;
box-sizing: border-box;
padding: 10px;}
.item.active{color: white; background-color: #6f51ed;}
.item:hover{
cursor: pointer;
}
.paddle {
position: absolute;
top: 0;
bottom: 0;
width: 2em;
}
.left-paddle {
left: 0;
color:#6f51ed;
background-color: transparent;
border-color: transparent;
outline: none;
font-size: x-large;
padding-bottom: 5px;
}
.right-paddle {
right: 0;
color:#6f51ed;
background-color: transparent;
border-color: transparent;
outline: none;
font-size: x-large;
padding-bottom: 5px;
}
.hidden {
display: none;
}
My Jquery/Js code is:
<script>
var scrollDuration = 450;
// paddles
var leftPaddle = document.getElementsByClassName('left-paddle');
var rightPaddle = document.getElementsByClassName('right-paddle');
// get items dimensions
var itemsLength = $('.item').length;
var itemSize = $('.item').outerWidth(true);
// get some relevant size for the paddle triggering point
var paddleMargin = 5;
// get wrapper width
var getMenuWrapperSize = function() {
return $('.menu-wrapper').outerWidth();
}
var menuWrapperSize = getMenuWrapperSize();
// the wrapper is responsive
$(window).on('resize', function() {
menuWrapperSize = getMenuWrapperSize();
});
// size of the visible part of the menu is equal as the wrapper size
var menuVisibleSize = menuWrapperSize;
// get total width of all menu items
var getMenuSize = function() {
return itemsLength * itemSize;
};
var menuSize = getMenuSize();
// get how much of menu is invisible
var menuInvisibleSize = menuSize - menuWrapperSize;
// get how much have we scrolled to the left
var getMenuPosition = function() {
return $('.menu').scrollLeft();
};
// finally, what happens when we are actually scrolling the menu
$('.menu').on('scroll', function() {
// get how much of menu is invisible
menuInvisibleSize = menuSize - menuWrapperSize;
// get how much have we scrolled so far
var menuPosition = getMenuPosition();
var menuEndOffset = menuInvisibleSize - paddleMargin;
// show & hide the paddles
// depending on scroll position
if (menuPosition <= paddleMargin) {
$(leftPaddle).addClass('hidden');
$(rightPaddle).removeClass('hidden');
} else if (menuPosition < menuEndOffset) {
// show both paddles in the middle
$(leftPaddle).removeClass('hidden');
$(rightPaddle).removeClass('hidden');
} else if (menuPosition >= menuEndOffset) {
$(leftPaddle).removeClass('hidden');
$(rightPaddle).addClass('hidden');
}
});
// scroll to left
$(rightPaddle).on('click', function() {
$('.menu').animate( { scrollLeft: itemSize}, scrollDuration);
});
// scroll to right
$(leftPaddle).on('click', function() {
$('.menu').animate( { scrollLeft: -itemSize }, scrollDuration);
});
</script>
Because you are scrolling to the same position, you need to add or subtract the itemSize to the current scroll position of .menu.
// scroll to left
$(rightPaddle).on('click', function() {
$('.menu').animate({
scrollLeft: $('.menu').scrollLeft() + itemSize
}, scrollDuration);
});
// scroll to right
$(leftPaddle).on('click', function() {
$('.menu').animate({
scrollLeft: $('.menu').scrollLeft() - itemSize
}, scrollDuration);
});
I am trying to create a scroll-able image gallery using javascript so i am able to create it but now i want it to work like an infinite loop i.e as soon as it reaches last image then on next click it should start with first image again
that's my html code
var width = 130; // image width
var count = 4; // visible images count
var list = carousel.querySelector('ul');
var listElems = carousel.querySelectorAll('li');
var position = 0;
// shift left
document.querySelector('.prev').onclick = function() {
position += width * count;
position = Math.min(position, 0);
list.style.marginLeft = position + 'px';
};
// shift right
document.querySelector('.next').onclick = function() {
position -= width * count;
position = Math.max(position, -width * (listElems.length - count));
list.style.marginLeft = position + 'px';
};
.carousel {
position: relative;
width: 508px;
padding: 10px 40px;
border: 1px solid #CCC;
border-radius: 15px;
background: #eee;
}
.carousel img {
width: 130px;
height: 130px;
}
.arrow {
position: absolute;
top: 40%;
padding: 0;
background: #ddd;
border-radius: 15px;
border: 1px solid gray;
font-size: 24px;
line-height: 24px;
color: #444;
}
.arrow:focus {
outline: none;
}
.arrow:hover {
background: #ccc;
cursor: pointer;
}
.prev {
left: 7px;
}
.next {
right: 7px;
}
.gallery {
width: 530px;
overflow: hidden;
}
.gallery ul {
height: 130px;
width: 10000px;
margin: 0;
padding: 0;
list-style: none;
transition: margin-left 350ms;
font-size: 0;
}
.gallery li {
display: inline-block;
}
<div class="carousel" id="carousel">
<button class="arrow prev">⇦</button>
<div class="gallery">
<ul class="images">
<li><img src="https://en.js.cx/carousel/1.png"></li>
<li><img src="https://en.js.cx/carousel/2.png"></li>
<li><img src="https://en.js.cx/carousel/3.png"></li>
<li><img src="https://en.js.cx/carousel/4.png"></li>
<li><img src="https://en.js.cx/carousel/5.png"></li>
<li><img src="https://en.js.cx/carousel/6.png"></li>
<li><img src="https://en.js.cx/carousel/7.png"></li>
<li><img src="https://en.js.cx/carousel/8.png"></li>
<li><img src="https://en.js.cx/carousel/9.png"></li>
<li><img src="https://en.js.cx/carousel/10.png"></li>
<li><img src="https://en.js.cx/carousel/5.png"></li>
<li><img src="https://en.js.cx/carousel/1.png"></li>
<li><img src="https://en.js.cx/carousel/8.png"></li>
</ul>
</div>
<button class="arrow next">⇨</button>
</div>
it works fine like on clicking buttons images are srcolling but i want it to be scrollable in infinite loop
You can do that by checking, before assigning the position's variable to the style.marginLeft :
for the next button, the position variable equals to -((the number of the carousel elements - four (as 4 cards should be shown)) multiplied by the width of an element) typically -((listElems.length - 4) * width) then assign 0 to position so the carousel starts over.
for the prev button, the position variable equals to 0 then assign to it -((the number of the carousel elements - four (as 4 cards should be shown)) multiplied by the width of an element).
Here's a demo :
var width = 130; // image width
var count = 4; // visible images count
var list = carousel.querySelector('ul');
var listElems = carousel.querySelectorAll('li');
var position = 0;
// shift left
document.querySelector('.prev').onclick = function() {
position += width * count;
position = Math.min(position, 0);
/** check if we have to loop back from the end **/
position === 0 && (position = -((listElems.length - 4) * width));
list.style.marginLeft = position + 'px';
};
// shift right
document.querySelector('.next').onclick = function() {
position -= width * count;
position = Math.max(position, -width * (listElems.length - count));
/** check if we have to loop back from the begining **/
position === -((listElems.length - 4) * width) && (position = 0);
list.style.marginLeft = position + 'px';
};
.carousel {
position: relative;
width: 508px;
padding: 10px 40px;
border: 1px solid #CCC;
border-radius: 15px;
background: #eee;
}
.carousel img {
width: 130px;
height: 130px;
}
.arrow {
position: absolute;
top: 40%;
padding: 0;
background: #ddd;
border-radius: 15px;
border: 1px solid gray;
font-size: 24px;
line-height: 24px;
color: #444;
}
.arrow:focus {
outline: none;
}
.arrow:hover {
background: #ccc;
cursor: pointer;
}
.prev {
left: 7px;
}
.next {
right: 7px;
}
.gallery {
width: 530px;
overflow: hidden;
}
.gallery ul {
height: 130px;
width: 10000px;
margin: 0;
padding: 0;
list-style: none;
transition: margin-left 350ms;
font-size: 0;
}
.gallery li {
display: inline-block;
}
<div class="carousel" id="carousel">
<button class="arrow prev">⇦</button>
<div class="gallery">
<ul class="images">
<li><img src="https://en.js.cx/carousel/1.png"></li>
<li><img src="https://en.js.cx/carousel/2.png"></li>
<li><img src="https://en.js.cx/carousel/3.png"></li>
<li><img src="https://en.js.cx/carousel/4.png"></li>
<li><img src="https://en.js.cx/carousel/5.png"></li>
<li><img src="https://en.js.cx/carousel/6.png"></li>
<li><img src="https://en.js.cx/carousel/7.png"></li>
<li><img src="https://en.js.cx/carousel/8.png"></li>
<li><img src="https://en.js.cx/carousel/9.png"></li>
<li><img src="https://en.js.cx/carousel/10.png"></li>
<li><img src="https://en.js.cx/carousel/5.png"></li>
<li><img src="https://en.js.cx/carousel/1.png"></li>
<li><img src="https://en.js.cx/carousel/8.png"></li>
</ul>
</div>
<button class="arrow next">⇨</button>
</div>
I want to write my own jQuery slider, which shows a small part of the next and previous image (for example 20px).
To achieve this, I have created a simple image slider, using float: left; to arrange all the images in one row inside a overflow: hidden div.
All my images got a fixed width of 200px. Because of this I calculate the margins of each image with the following sass:
img {
float: left;
display: block;
margin: 0 calc((100vw - 200px) / 4 - 20px);
&:first-child {
margin-left: calc((100vw - 200px) / 2);
}
&:last-child {
margin-right: calc((100vw - 200px) / 2);
}
}
This works great and positions every image as it should be.
While trying to animate the slider using transform: translateX(); I am totally lost calculating the amount of pixels (in vw/%/px) I need to translateX the $('#slider').
How can I calculate the translateX value to slide to each image centered?
$(document).ready(function(){
document.getElementById('slider').ondragstart = function() { return false; };
var slider = $('#slider'),
images = slider.find('img'),
imageCount = images.length,
currentIndex = 0;
slider.width( imageCount * 100 + "vw");
var slideLeft = function () {
if ( currentIndex >= imageCount - 1 ) {
console.log("Last image reached");
return;
}
currentIndex += 1;
console.log("Slide left");
slider.css("transform", "translateX(" + currentIndex * -10 + "vw)");
}
var slideRight = function () {
if ( currentIndex === 0 ) {
console.log("First image reached");
return;
}
currentIndex -= 1;
console.log("Slide right");
slider.css("transform", "translateX(" + currentIndex * -10 + "vw)");
}
$('#right').on('click', function(){
slideLeft();
});
$('#left').on('click', function(){
slideRight();
});
});
html, body {
margin: 0;
padding: 0;
}
#slider-container {
overflow: hidden;
height: 300px;
background: rgba(0, 0, 0, 0.05);
margin: 5vw 0;
width: 100vw;
}
#slider {
height: 300px;
transition: transform .3s ease-in-out;
transform: translateX(0);
}
#slider img {
float: left;
display: block;
margin: 0 calc((100vw - 200px) / 4 - 20px);
}
#slider img:first-child {
margin-left: calc((100vw - 200px) / 2);
}
#slider img:last-child {
margin-right: calc((100vw - 200px) / 2);
}
#controls {
position: relative;
width: 100vw;
display: block;
height: calc(10vw + 100px);
}
#controls .arrow {
display: block;
width: 100px;
top: 5vw;
background: lightgray;
height: 100px;
left: 5vw;
position: absolute;
font-size: 100px;
line-height: 80px;
font-weight: bold;
text-align: center;
cursor: pointer;
}
#controls .arrow:hover {
background: lightblue;
}
#controls #right {
left: auto;
right: 5vw;
}
p {
margin: 0 5vw 5vw;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="slider-container">
<div id="slider">
<img src="https://unsplash.it/200/300?image=1077" alt="img-1">
<img src="https://unsplash.it/200/300?image=1076" alt="img-2">
<img src="https://unsplash.it/200/300?image=1072" alt="img-3">
<img src="https://unsplash.it/200/300?image=1063" alt="img-4">
<img src="https://unsplash.it/200/300?image=1061" alt="img-5">
</div>
</div>
<div id="controls">
<div id="left" class="arrow">‹</div>
<div id="right" class="arrow">›</div>
</div>
<p>Currently every scroll click scrolls a random amount to the left or right. This needs to be fixed, so that every image is centered after the slide.</p>
I had made few updates in your script.
try with this script
$(document).ready(function(){
document.getElementById('slider').ondragstart = function() { return false; };
var slider = $('#slider'),
images = slider.find('img'),
imageCount = images.length,
currentIndex = 0;
slider.width( imageCount * 100 + "vw");
var $this = $("#slider-container");
var offset = $this.offset();
var width = $this.width();
var centerX = (offset.left + width / 2 ) + (images.width() / 2) - 40;
var slideLeft = function () {
if ( currentIndex >= imageCount - 1 ) {
console.log("Last image reached");
return;
}
currentIndex += 1;
console.log("Slide left");
slider.css("transform", "translateX(-" + (currentIndex * centerX) + "px)");
}
var slideRight = function () {
if ( currentIndex === 0 ) {
console.log("First image reached");
return;
}
currentIndex -= 1;
console.log("Slide right");
slider.css("transform", "translateX(-" + (currentIndex * centerX) + "px)");
}
$('#right').on('click', function(){
slideLeft();
});
$('#left').on('click', function(){
slideRight();
});
});
check this fiddle : jsFiddle
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 was trying to move the divs (here it's question number) based on the prev and next button. So that the selected question is always visible on screen.
Here is the demo : http://jsfiddle.net/arunslb123/trxe4n3u/12/
Screen :
click and question number and click prev or next button to understand my issue.
My code :
$("#next")
.click(function () {
$(".c.current-question")
.each(function () {
var divIdx = $(this)
.attr('id');
var scrollTo = $('#' + divIdx)
.position()
.left;
$("#scrollquestion")
.animate({
'scrollLeft': scrollTo
}, 800);
});
});
$("#prev")
.click(function () {
$(".c.current-question")
.each(function () {
var divIdx = $(this)
.attr('id');
var scrollTo = $('#' + divIdx)
.position()
.left;
$("#scrollquestion")
.animate({
'scrollLeft': -scrollTo
}, 800);
});
});
Using scrollLeft is a bit tricky. I did a small redo of your use-case based on positioning and then moving it based on left of the container. The tricky part is to reliably calculate the negative position when scrolled to the extreme right. Also, need to take into account the widths and margins.
Check the below snippet:
var $wrap = $("#numWrap"), $strip = $("#strip"),
$leftArrow = $(".wrapper > .arrows").first(),
wrapWidth = $wrap.width() + $leftArrow.width(),
margin = 10;
fill(20); select($(".numberItem").first());
$strip.on("click", ".numberItem", function() { select($(this)); });
function select($elem) {
$(".numberItem").removeClass("selected");
$elem.addClass("visited").addClass("selected");
focus($elem[0]);
}
function focus(elem) {
var stripPos = $strip.position(),
numPos = $(elem).offset(),
elemWidth = $(elem).width() + margin,
numRight = numPos.left + elemWidth;
if (numRight > wrapWidth) {
$strip.css({"left": stripPos.left - elemWidth});
}
if (numPos.left < (margin + $leftArrow.width())) {
$strip.css({"left": stripPos.left + elemWidth});
}
}
$(".wrapper").on("click", "a.arrow", function() {
var stripPos = $strip.position();
if (this.id == "lft") {
$strip.css({"left": stripPos.left + (wrapWidth / 2)});
} else {
$strip.css({"left": stripPos.left - (wrapWidth / 2)});
}
});
$(".controls").on("click", "a.arrow", function() {
var $sel = $(".selected"), numPos, $sel, elemWidth;
$elem = $sel.length > 0 ? $sel.first() : $(".numberItem").first();
if (this.id == "lft") {
$sel = $elem.prev().length > 0 ? $elem.prev() : $elem;
select($sel);
} else {
$sel = $elem.next().length > 0 ? $elem.next() : $elem;
select($sel);
}
numPos = $sel.offset(); elemWidth = $sel.width() + margin;
numRight = numPos.left + elemWidth;
if (numPos.left > wrapWidth) {
$strip.css({"left": -($sel.text()) * $sel.width() });
}
if (numRight < 0) {
$strip.css({"left": +($sel.text()) * $sel.width() });
}
});
function fill(num){
for (var i = 1; i <= num; i++) {
var $d = $("<a href='#' class='numberItem'>" + i + "</a>");
$strip.append($d);
}
}
* { box-sizing: border-box; padding: 0; margin: 0; font-family: sans-serif; }
div.wrapper {
background-color: #ddd; width: 100vw; height: 64px;
clear: both; overflow: hidden; margin-top: 16px;
}
div.arrows {
float: left; width: 10%; min-width: 24px; height: 64px; line-height: 64px;
text-align: center; vertical-align: middle; overflow: hidden;
}
div.numWrap {
float: left; height: 64px; line-height: 64px;
width: 80%; vertical-align: middle;
overflow: hidden; position: relative;
}
div.strip {
position: absolute; left: 0px;
width: auto; white-space: nowrap;
transition: left 1s;
}
a.numberItem {
display: inline-block; text-align: center; margin: 0px 8px;
background-color: #fff; border-radius: 50%; width: 48px; height: 48px;
font-size: 1.2em; line-height: 48px; text-decoration: none;
}
a.numberItem.visited { background-color: #fff; color: #000; border: 2px solid #01aebc; }
a.numberItem.selected { background-color: #01aebc; color: #fff; }
div.controls { clear: both; }
div.controls > div.arrows { width: auto; margin: 0 12px; }
a, a:focus, a:active, a:link, a:visited {
display: inline-block;
text-decoration: none; font-weight: 600;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="arrows">
<a id="lft" class="arrow" href="#">〈</a>
</div>
<div id="numWrap" class="numWrap">
<div id="strip" class="strip"></div>
</div>
<div class="arrows">
<a id="rgt" class="arrow" href="#">〉</a>
</div>
</div>
<div class="controls">
<div class="arrows">
<a id="lft" class="arrow" href="#">〈 Previous</a>
</div>
<div class="arrows">
<a id="rgt" class="arrow" href="#">Next 〉</a>
</div>
<div>
Explanation:
Using absolute positioning on the number container, which is nested to get 100% width.
Markup:
<div class="wrapper">
<div class="arrows"><a id="lft" class="arrow" href="#">〈</a></div>
<div id="numWrap" class="numWrap">
<div id="strip" class="strip"></div> <!-- nesting here -->
</div>
<div class="arrows"><a id="rgt" class="arrow" href="#">〉</a></div>
</div>
CSS:
div.wrapper {
background-color: #ddd; width: 100vw; height: 64px;
clear: both; overflow: hidden; margin-top: 16px;
}
div.arrows {
float: left; width: 10%; min-width: 24px; height: 64px; line-height: 64px;
text-align: center; vertical-align: middle; overflow: hidden;
}
div.numWrap {
float: left; height: 64px; line-height: 64px;
width: 80%; vertical-align: middle;
overflow: hidden; position: relative; /* relatively positioned */
}
div.strip {
position: absolute; left: 0px; /* absolutely positioned */
width: auto; white-space: nowrap;
transition: left 1s; /* instead of jquery animate */
}
With this structure, we can now use left to control the scrolling.
For partially obscured numbers, try to gently focus-in (nudge into view) a number which is partially obscured. This can be done by checking the position relative to parent and adding the width/margin to it and also accounting for width of the left arrow (it might peep thru).
Javascript:
function focus(elem) {
var stripPos = $strip.position(),
numPos = $(elem).offset(),
elemWidth = $(elem).width() + margin,
numRight = numPos.left + elemWidth;
// if it is towards right side, nudge it back inside
if (numRight > wrapWidth) {
$strip.css({"left": stripPos.left - elemWidth});
}
// if it is towards left side, nudge it back inside
if (numPos.left < (margin + $leftArrow.width())) {
$strip.css({"left": stripPos.left + elemWidth});
}
}
Once the user has scrolled the list too far and then tries to click on previous / next buttons to select a question, then we need to move the entire container upto the selected number. We can easily do this by multiplying the question number with element width and then changing the left in positive (if towards right) or in negative (if towards left).
Javascript:
// if left of element is more than the width of parent
if (numPos.left > wrapWidth) {
$strip.css({"left": -($sel.text()) * $sel.width() });
}
// if right of element is less than 0 i.e. starting position
if (numRight < 0) {
$strip.css({"left": +($sel.text()) * $sel.width() });
}
Here is a fiddle to play with: http://jsfiddle.net/abhitalks/aw166qhx/
You will need to further adapt it to your use-case, but you get the idea.