Reputation: 195
For example let's say that I have a div element with 100%
width and 100px
height. Inside that div I have 6 div elements floated left, with overflow-x
enabled. What I want to achieve is, that user can scroll through loop of these divs (so that last div element is followed by first - infinite loop).
Any idea how to approach?
Upvotes: 4
Views: 592
Reputation: 34160
You can use jQuery insertAfter
and insertBefore
functions
$('.next').click(function(){
var last = $('#parent').find('div').last();
$('#parent').find('div').first().insertAfter(last);
});
$('.prev').click(function(){
var first= $('#parent').find('div').first();
$('#parent').find('div').last().insertBefore(first);
});
Here is the DEMO
Upvotes: 5
Reputation: 42736
append/prepend the first/last element respectively depending on the direction you are going.
jQuery(window).keyup(function(e){
switch(e.keyCode){
case 37:
left();
break;
case 39:
right();
break;
}
})
var container=jQuery("#container");
function left(){
container.find(".item:last").prependTo(container);
}
function right(){
container.find(".item:first").appendTo(container);
}
html,body {
width:100vw;
height:100vh;
padding:0px;
margin:0px;
}
#container {
width:100vw;
height:100px;
display:flex;
position:relative;
}
.item {
width:100px;
height: 94px;
margin:3px;
flex:0 1 100px;
}
.red {background:#F00;}
.green {background:#0F0;}
.blue {background:#00F;}
.yellow {background:#FF0;}
.turq {background:#0FF;}
.purple {background:#F0F;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
<div class="item red"></div>
<div class="item green"></div>
<div class="item blue"></div>
<div class="item yellow"></div>
<div class="item turq"></div>
<div class="item purple"></div>
</div>
Upvotes: 5