I have been working on this functionality where I have 5 circles then when a button is clicked they all move down the page one at a time in order. I am trying to get them to go down in a random order. (if not random at least something that doesn't make them fall in order)
JsFiddle: https://jsfiddle.net/n12zj90p/2/
HTML:
<div class="container">
<button>CLICK</button>
<div class="circle circle-1"></div>
<div class="circle circle-2"></div>
<div class="circle circle-3"></div>
<div class="circle circle-4"></div>
<div class="circle circle-5"></div>
</div>
CSS:
.circle{
width: 40px;
height: 40px;
position: absolute;
background: red;
border-radius: 100%;
}
.circle-1{ top: 10em; left: 10em; }
.circle-2{ top: 20em; left: 20em; }
.circle-3{ top: 30em; left: 30em; }
.circle-4{ top: 40em; left: 40em; }
.circle-5{ top: 50em; left: 50em; }
button{ padding: 10px 50px; display: table; margin: auto; }
JQUERY:
$(document).ready(function(){
var $c = $(".circle");
$("button").click(function(){
$c.each(function(i, elem){
$(elem).delay(i * 500).animate({top:"300em"}, { duration: 2000, complete: function(){
//just something to do after the animation has been completed, you can disregaurd this area
}
});//animate end
});//each end
});
});
var $c = $(".circle"); is an array. So you just need to randomly shuffle it before doing each on it
function shuffle(o){
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
shuffle($c).each(...
Shuffle comes from here
Not sure I deserve any credit for this because it was Pointy's idea, but here's a code that's working and pretty simple:
$(document).ready(function(){
var $c = $(".circle");
$("button").click(function(){
$c.each(function(i, elem){
var rando_time = Math.floor((Math.random() * 600) + 1);
$(elem).delay(i * rando_time).animate({top:"300em"}, { duration: 2000, complete: function(){
//just something to do after the animation has been completed, you can disregaurd this area
}
});//animate end
});//each end
});
});
Related
I need the image in the both divs below to be in the same position even if the other div changes height or width. I have tried calculating top and left to % from px but still it is not working. I have also tried calculating the % of how big or small other div is and adding or removing the top and left to the image in other div and still no luck.
To check the issue, drag the image around inside the first div and click on submit. Now the image inside the bottom div should be in the same position as the above div, same top and left distance.
Please help. Thanks.
Here is the fiddle : https://jsfiddle.net/kashyap_s/gLdt62nh
var zoomLevel = 1;
$("#myimage").draggable({
start: function() {
},
stop: function() {
}
});
$('#save').click(function() {
var topcss = $('#myimage').css('top');
var leftcss = $('#myimage').css('left');
var transformcss = zoomLevel;
topcss = topcss.replace('px', '');
leftcss = leftcss.replace('px', '');
topcss = parseInt(topcss);
leftcss = parseInt(leftcss);
var parentWidth = $('#dragDiv').outerWidth()
var parentHeight = $('#dragDiv').outerHeight()
console.log('leftcss', leftcss, 'width', parentWidth)
console.log('topcss', topcss, 'height', parentHeight)
var percentLeft = leftcss / parentWidth * 100;
var percentTop = topcss / parentHeight * 100;
console.log('percentLeft', percentLeft, 'percentTop', percentTop)
transformcss = parseFloat(transformcss).toFixed(2);
var result = {
"top": topcss,
"left": leftcss,
'percentTop': percentTop,
'percentLeft': percentLeft,
'parentWidth': parentWidth,
'parentHeight': parentHeight,
"transform": "scale(" + transformcss + ")"
};
var output = JSON.stringify(result);
console.log('output', output)
$("#newimg").css({
'left': leftcss
});
$("#newimg").css({
'top': topcss
});
});
.transperentimage {
width: 497px;
height: 329px;
border: 1px solid black;
margin: 0 auto;
}
#bigimg {
width: 651px;
height: 431px;
border: 1px solid black;
margin: 0 auto;
}
img {
border: 2px solid red;
padding: 3px;
width: auto;
height: auto;
cursor: move;
max-height: 180px;
}
#newimg {
position: absolute;
max-height: 180px;
width: auto!important;
height: auto!important;
max-width: 100%!important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="transperentimage" id="dragDiv">
<img id="myimage" src="agent.png">
</div>
<button id="save">Save</button>
<div id="bigimg">
<img id="newimg" src="agent.png" />
</div>
$(function() {
$("#logo1").draggable({
containment: "parent",
drag: function() {
}
});
});
function setpos() {
var image1_w = $("#logo1").width();
var div1_w = $(".div1").width();
var image2_w = $("#logo2").width();
var div2_w = $(".div2").width();
var image1_h = $("#logo1").height();
var div1_h = $(".div1").height();
var image2_h = $("#logo2").height();
var div2_h = $(".div2").height();
var div1_aw = div1_w - image1_w;
var div2_aw = div2_w - image2_w;
var div1_ah = div1_h - image1_h;
var div2_ah = div2_h - image2_h;
var div
var xPos = $('#logo1').css('left');
var yPos = $('#logo1').css('top');
var ratio_w = parseFloat(div1_aw) / parseFloat(div2_aw);
var ratio_h = parseFloat(div1_ah) / parseFloat(div2_ah);
//let act = 1.39;
var div2_nw = parseFloat(xPos) / ratio_w;
var div2_nh = parseFloat(yPos) / ratio_h;
$("#posX").text('Div left:' + div2_nw);
$("#posA").text('Div Top:' + div2_nh);
$("#logo2").css({
'left': div2_nw,
'top': div2_nh
});
}
.div1 {
width: 497px;
height: 329px;
border: 1px solid black;
}
.div2 {
width: 651px;
height: 431px;
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script
src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
crossorigin="anonymous"></script>
<p>Drag my logo.</p>
<div class="div1">
<img src="https://smteg.sefion.com/perfectmetal/assets/ui/sefion.jpg" style=" position: relative; left: 0px; top: 0px;" width="100" id="logo1">
</div>
<br>
<div class="div2">
<img style="position: relative;left: 0px;top: 0px" src="https://smteg.sefion.com/perfectmetal/assets/ui/sefion.jpg" width="100" id="logo2">
</div>
<br>
<button onclick="setpos();">
Save
</button>
<div id="posX">
</div>
<div id="posA">
</div>
<div id="posz">
</div>
<div id="posZ1">
</div>
Solved! check this out
HTML
<p>Drag my logo.</p>
<div class="div1">
<img src="https://smteg.sefion.com/perfectmetal/assets/ui/sefion.jpg" style=" position: relative; left: 0px; top: 0px;" width="100" id="logo1">
</div>
<br>
<div class="div2">
<img style="position: relative;left: 0px;top: 0px" src="https://smteg.sefion.com/perfectmetal/assets/ui/sefion.jpg" width="100" id="logo2">
</div>
<br>
<button onclick="setpos();">
Save
</button>
<div id="posX"></div>
<div id="posA"></div>
JS CODE
$( function() {
$( "#logo1" ).draggable(
{
containment: "parent",
drag: function() {
}
}
);
} );
function setpos()
{
var image1_w = $("#logo1").width();
var div1_w = $(".div1").width();
var image2_w = $("#logo2").width();
var div2_w = $(".div2").width();
var image1_h = $("#logo1").height();
var div1_h = $(".div1").height();
var image2_h = $("#logo2").height();
var div2_h = $(".div2").height();
var div1_aw = div1_w-image1_w;
var div2_aw = div2_w-image2_w;
var div1_ah = div1_h-image1_h;
var div2_ah = div2_h-image2_h;
var div
var xPos = $('#logo1').css('left');
var yPos = $('#logo1').css('top');
var ratio_w = parseFloat(div1_aw)/parseFloat(div2_aw);
var ratio_h = parseFloat(div1_ah)/parseFloat(div2_ah);
//let act = 1.39;
var div2_nw = parseFloat(xPos)/ratio_w;
var div2_nh = parseFloat(yPos)/ratio_h;
$("#posX").text('Div left:' + div2_nw);
$("#posA").text('Div Top:' + div2_nh);
$("#logo2").css({ 'left' : div2_nw, 'top' : div2_nh});
}
CSS
.div1{
width: 497px;
height: 329px;
border: 1px solid black;
}
.div2{
width: 651px;
height: 431px;
border: 1px solid black;
}
For your newimg, the parent must have a position that is relative. This way, the absolute positioning will be relative to the parent and not the body.
An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed).
Consider the following code.
$(function() {
var zoomLevel = parseFloat(1 - ($("#dragDiv").outerWidth() / $("#bigimg").outerWidth()).toFixed(2));
function log(str) {
if ($(".log").length) {
$(".log").html(str);
} else {
$("<div>", {
class: "log"
}).html(str).appendTo("body");
}
}
function getPos(el) {
var par = $(el).parent();
var pos = {
top: parseInt($(el).css("top")),
left: parseInt($(el).css("left")),
zoom: "scale(" + (1 + zoomLevel) + ")",
parWidth: par.outerWidth(),
parHeight: par.outerHeight()
};
pos['perLeft'] = parseFloat((pos.left / pos.parWidth).toFixed(2)) * 100;
pos['perTop'] = parseFloat((pos.top / pos.parHeight).toFixed(2)) * 100;
return pos;
}
$("#myimage").draggable({
containment: "parent",
drag: function(e, ui) {
log("Left: " + ui.position.left + ", Top: " + ui.position.top);
},
start: function() {
// coordinates('#myimage');
},
stop: function() {
// coordinates('#myimage');
var p = getPos(this);
$(this).attr("title", JSON.stringify(p));
}
});
$('#save').click(function() {
var result = getPos($("#myimage"));
var output = JSON.stringify(result);
var nLeft = Math.round(result.perLeft * (1 + zoomLevel)) + "%";
var nTop = Math.round(result.perTop * (1 + zoomLevel)) + "%"
console.log(output, nLeft, nTop);
$("#newimg").css({
left: nLeft,
top: nTop
});
var p = getPos($("#newimg"));
$("#newimg").attr("title", JSON.stringify(p));
});
});
.transperentimage {
width: 497px;
height: 329px;
border: 1px solid black;
margin: 0 auto;
}
#bigimg {
width: 651px;
height: 431px;
border: 1px solid black;
margin: 0 auto;
position: relative;
}
img {
border: 2px solid red;
padding: 3px;
width: auto;
height: auto;
cursor: move;
/* max-width: 100%; */
max-height: 180px;
}
#newimg {
position: absolute;
max-height: 180px;
width: auto!important;
height: auto!important;
max-width: 100%!important;
}
.log {
font-size: 11px;
font-family: "Arial";
position: absolute;
top: 3px;
left: 3px
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="transperentimage" id="dragDiv">
<img id="myimage" src="https://i.imgur.com/4ILisqH.jpg">
</div>
<button id="save">Save</button>
<div id="bigimg">
<img id="newimg" src="https://i.imgur.com/4ILisqH.jpg" />
</div>
See More: https://www.w3schools.com/css/css_positioning.asp
Updated
Looking at it further, I am guessing that you might be trying to reposition the bigimg in relationship to myimage position. This requires scaling the percentage.
For example, if we move myimage to the far left, it will be at left: 247, and this is roughly 49% of 499px. 49% of 653 is around 319, and this would not place the image where we want it. We want it at 401.
bigimg is about 24% larger than dragDiv, so we need to scale our percentage. 49 * 1.24 = 60.74, round up to 61. 653 * .61 = 398.33 so better yet not perfect.
JS: My problem is in running the following JS script, it's supposed to be very easy ,i think, but i can't understand why won't it run. I've just started coding and i'm already stuck in this problem. I want the text to go up (by increasing the bottom in CSS) for 5px until it reaches pos=6 ; then clearInterval should do its job.
CSS: I've put the position of div's to RELATIVE as i've read in some tutorials but didn't put the " container's " position to ABSOLUTE, may it be the problem?
<html>
<head>
<style>
html {
height: 100%;
}
body {
height: ;
width: 100%;
background-color: ;
margin: 0px;
padding: 0px;
}
#generale {
height: 100%;
width: 100%;
}
#intestazione {
height: 7%;
width: 100%;
float: left;
background-image: url(immagini/sfumatura.png);
position: static;
}
#profilo {
position: static;
float: right;
width: 12%;
height: 100%;
}
.testo_rialzato {
position: relative;
float: right;
width: auto;
height: 100%;
padding-left: 20px;
padding-right: 20px;
background-color: transparent;
}
</style>
</head>
<body>
<div id="generale">
<div id="intestazione">
<div id="profilo"></div>
<div class="testo_rialzato sumba">
<p>Sp</p>
</div>
<div class="testo_rialzato ap">
<p>App</p>
</div>
<div class="testo_rialzato te">
<p>Te</p>
</div>
<div class="testo_rialzato do">
<p>Dom</p>
</div>
<div class="testo_rialzato big">
<p style="line-height:70%; margin-top:8px; text-align:center;">Big</p>
</div>
</div>
<script>
var ez = document.querySelectorAll(".sumba , .ap , .te , .do, .big");
ez.onmouseover = alza();
var intervallo = setInterval(alza, 100);
function alza() {
var pos = 0;
if (pos = 6) {
clearInterval(intervallo);
} else {
ez.style.bottom = pos + "px";
}
}
</script>
</div>
</body>
</html>
First thing is , why declaring you are using event on an array of dome node (result of querySelectorAll will return array of domenodes ) so in order to attach mouseover and also apply some style you have to loop around those nodes .
Seconde thing while declaring set interval, its usless to use mousemovehere ?
Also the condition if is wrong you're using assignment , so you have to use == or === in order to make comaparison .
See below snippet :
var ez = document.querySelectorAll(".sumba , .ap , .te , .do, .big");
var pos = 0;
var intervallo = setInterval(alza, 100);
ez.forEach(function(el){
el.addEventListener("mouseover", alza);
})
function alza() {
if (pos == 25) {
clearInterval(intervallo);
} else {
ez.forEach(function(el){
el.style.bottom = pos + "px";
});
pos++;
}
}
.sumba, .ap {
position:absolute;
}
.ap {
color:red;
left:40px
}
<!-- begin snippet: js hide: false console: true babel: false -->
<div class="sumba">Text</div>
<div class="ap">Text 2</div>
try this
<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
}
</style>
<body>
<p>
<button onclick="myMove()">Click Me</button>
</p>
<div id ="container">
<div id ="animate">ggg</div>
</div>
<script>
function myMove() {
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.left = pos + 'px';
}
}
}
</script>
</body>
</html>
I have a function which counts the number of line breaks in a div, depending on the width of the window. While the functions works fine when placed in the $(window).on('resize') function, it does not work when put in $(document).ready() function. I want it to work right on page load, and also window resize, how do I support both?
JSFiddle
Javascript/jQuery:
// functions called in both document.ready() and window.resize
$(document).ready(function(){
var lineCount = getLineCount();
postItems(lineCount);
$('.answer').text("Ready");
});
$(window).on('resize', function(){
var lineCount = getLineCount();
postItems(lineCount);
$('.answer').text("Number of lines: " + lineCount);
});
// calculates the amount of lines required to hold the items
function getLineCount() {
var lineWidth = $('.line').width();
var itemWidthSum = 0;
var lineCount=1;
$('.item').each(function(index, element) {
if((lineWidth - itemWidthSum) > ($(element).outerWidth())) {
itemWidthSum = itemWidthSum + $(element).outerWidth();
} else {
lineCount++;
itemWidthSum = $(element).outerWidth();
}
});
return lineCount;
}
// overlays rows for the amount of linebreaks
function postItems(lineCount){
var container = $('<div />');;
for(var i = 1; i <= lineCount; i++) {
container.append('<div class="line">' + i + '</div>');
}
$('.line-wrap').html(container);
}
You'll see at the start of the page, it incorrectly shows 17 lines, and then once you resize it will show the correct amount.
The issue lies in the first line of getLineCount(). Originally you had
var lineWidth = $('.line').width();
but no elements with the class "line" exist yet on your page (since they get added in your postItems() method. I changed it to
var lineWidth = $(".container").width();
instead, and now your code should be working. Snippet posted below:
$(document).ready(function(){
var lineCount = getLineCount();
postItems(lineCount);
$('.answer').text("Ready");
});
$(window).on('resize', function(){
var lineCount = getLineCount();
postItems(lineCount);
$('.answer').text("Number of lines: " + lineCount);
});
// calculates the amount of lines required to hold the items
function getLineCount() {
var lineWidth = $('.container').width();
var itemWidthSum = 0;
var lineCount=1;
$('.item').each(function(index, element) {
if((lineWidth - itemWidthSum) > ($(element).outerWidth())) {
itemWidthSum = itemWidthSum + $(element).outerWidth();
} else {
lineCount++;
itemWidthSum = $(element).outerWidth();
}
});
return lineCount;
}
// overlays rows for the amount of linebreaks
function postItems(lineCount){
var container = $('<div />');;
for(var i = 1; i <= lineCount; i++) {
container.append('<div class="line">' + i + '</div>');
}
$('.line-wrap').html(container);
}
body {
text-align:center;
}
.answer {
position: fixed;
left: 0;
bottom: 0;
}
.container {
position: relative;
width: 50%;
margin: 0 auto;
border: 1px solid #e8e8e8;
display: inline-block;
}
.item {
height: 50px;
padding:0 10px;
background-color: #aef2bd;
float: left;
opacity:0.2;
white-space: nowrap;
}
.line-wrap {
position: absolute;
border: 1px solid red;
width: 100%;
height: 100%;
top:0; left: 0;
}
.line {
height: 50px;
width: 100%;
background-color: blue;
opacity:0.5;
color: white;
transition: all 0.5s ease;
}
.line:hover {
background-color: yellow;
color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="item-wrap">
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
</div>
<div class="line-wrap">
</div>
</div>
<h1 class="answer"></h1>
I'm trying to create div boxes step by step and animate them for several times when a button is pressed. I have a running code, and everything is going well. It goes right to the endhost, then it goes left again to its original place. This is mainly what I do, and also the demo is found here: http://jsfiddle.net/LSegC/1/
Now what I want to do is to increase the number of whole animated DIVs one-by-one (as it is now) up to 3 Divs, but then have exponential increase on the total number of DIVs. So the total number of animated DIVs will be like 1, 2, 3, and then 4, 8, 16, etc.
Remember, my problem is not with the number being shown inside the DIV, it's actually that how many DIVS are being created! So I want for instance 8 DIVs, numbered from 1 to 8 animated. Hope it is now clear.
$(document).ready(function(){
$("button").click(function() {
var d = $(".t").fadeIn();
var speed = +$("#number1").val();
d.animate({left:'+=230px'}, speed);
d.animate({left:'+=230px'}, speed);
d.animate({top:'+=20px', backgroundColor: "#f09090", text:'12'}, speed/4, "swing", function() {
$('.span', this).fadeOut(100, function() {
$(this).text(function() {
return 'a' + $(this).text().replace('a', '');
}).fadeIn(100);
});
});
d.delay(1000).animate({left:'-=230px'}, speed);
d.animate({left:'-=230px'}, speed);
d.fadeOut().promise().done(function() {
d.last().after(function() {
var top = +$(this).css('top').replace('px', ''),
number = +$(this).data('number') + 1,
$clone = $(this).clone();
$clone.data('number', number).css('top', top + 20);
$clone.find('.span').text(number);
return $clone;
});
d.find('.span').text(function() {
return $(this).text().replace('a', '');
});
})
});
EDIT
Your code was too hard to manipulate as it was, I recreated the whole thing:
HTML:
<img id="streamline1" src="https://cdn3.iconfinder.com/data/icons/streamline-icon-set-free-pack/48/Streamline-04-48.png" />
<img id="LAN" src="https://cdn1.iconfinder.com/data/icons/ecqlipse2/NETWORK%20-%20LAN.png" />
<img src="https://cdn3.iconfinder.com/data/icons/streamline-icon-set-free-pack/48/Streamline-04-48.png" id="streamline" />
<div id="mid"></div>
<div id="bottom"></div>
<div>Speed (mS):
<input value="500" id="speed" type="number" style="position: relative"></input>
<button>Apply!</button>
<!-- dynamic area -->
<div class="packets"></div>
</div>
JS:
$(document).ready(function () {
var count = 0;
var items = 0;
var packetNumber = 0;
var speed = 0;
$("button").click(function () {
if (count < 4) {
items = items + 1;
count++;
} else {
items = items * 2;
}
speed = $("#speed").val();
createDivs(items);
animateDivs();
});
function createDivs(divs) {
packetNumber = 1;
var left = 60;
for (var i = 0; i < divs; i++) {
var div = $("<div class='t'></div>");
div.appendTo(".packets");
$("<font class='span'>" + packetNumber + "</font>").appendTo(div);
packetNumber++;
div.css("left",left+"px");
div.hide();
left += 20;
}
}
function animateDivs() {
$(".t").each(function () {
var packet = $(this);
packet.show();
packet.animate({
left: '+=230px'
}, speed);
packet.animate({
left: '+=230px'
}, speed);
packet.animate({
top: '+=20px',
backgroundColor: "#f09090",
text: '12'
}, speed / 4, "swing", function () {
$('.span').fadeOut(100, function () {
$(this).text(function () {
return 'a' + $(this).text().replace('a', '');
}).fadeIn(100);
});
});
packet.delay(1000).animate({left:'-=230px'}, speed);
packet.animate({left:'-=230px'}, speed);
}).promise().done(function(){
$(".packets").empty();});
}
});
CSS:
#bottom {
border: 1px dashed gray;
position: absolute;
left: 55px;
height: 20px;
width: 500px;
opacity: 0.5;
top: 30px;
z-index=-1;
}
#mid {
border: 1px dashed gray;
position: absolute;
left: 55px;
height: 20px;
width: 500px;
opacity: 0.5;
top: 10px;
z-index=-1;
}
.t {
display: inline-block;
position: absolute;
top: 10px;
left: 60px;
text-align: center;
vertical-align: middle;
width: 20px;
height: 20px;
background-color: lightgreen
}
#streamline {
width: 50px;
height: 50px;
right: 0px;
position: fixed;
left: 548px;
}
#streamline1 {
left: 0px;
width: 50px;
height: 50px;
}
#LAN {
width: 50px;
height: 50px;
left: 275px;
position: fixed;
}
.packets {
display: inline;
}
FIDDLE: http://jsfiddle.net/54hqm/3/
It was tough for me to follow the code also, but I cut it back quite a bit, came up with a "one-way" "empiric" approach. FIDDLE
The speed can be adjusted by the change in the increment (inc), but there are a variety of methods that can be used.
Can you be more specific about what you mean by "exponential"? Do you mean an exponential speed increase across the div, or rather a speed increase until you get to 50%, then a decrement in speed.
JS
$("button").click(function() {
var speed = 1000;
var d = $('.mover');
d.show();
var inc = 1;
for (var i=0; i<290; i=i+inc)
{
d.animate({ left: i,
easing: 'linear'}, 1);
if (inc < 11)
{
inc = inc + 1;
} else {
inc = inc - 1;
}
}
});
How can I make the carousel center the item I've clicked to the middle? I've looked everywhere for an answer but they're not straight answers... Can someone help me in this, please?
This is what I've done so far: http://jsfiddle.net/sp9Jv/
HTML:
<div id="wrapper">
<div id="carousel">
prev
next
<div class="viewport">
<ul>
<li>Un</li>
<li>Deux</li>
<li>Trois</li>
<li>Quatre</li>
<li>Cinq</li>
<li>Six</li>
<li>Sept</li>
<li>Huit</li>
</ul>
</div>
<!-- viewport -->
</div>
<!-- carousel -->
</div>
<!-- wrapper -->
JavaScript:
var carousel = $('#carousel'),
prev = carousel.find('.prev'),
next = carousel.find('.next'),
viewport = carousel.find('.viewport'),
item = viewport.find('li'),
itemWidth = item.outerWidth(true),
itemNum = item.length,
itemList = viewport.find('ul');
itemList.width(itemWidth * itemNum);
var moveCarousel = function(dir) {
itemList.animate({ left: '-=' + (itemWidth * dir) + 'px' }, 400);
};
//prev
prev.on('click', function(e) {
e.preventDefault();
moveCarousel(-1);
});
//next
next.on('click', function(e) {
e.preventDefault();
moveCarousel(1);
});
//carousel item
item.on('click', 'a', function(e) {
var self = $(this),
selfIndex = self.index(),
distance = itemList.width() / 2,
selfPos = self.position(),
selfPosLeft = selfPos.left,
viewportPosLeft = viewport.position().left;
e.preventDefault();
//move item to middle, but it doesn't work...
if (selfPosLeft > Math.floor(viewport.width())/3) {
itemList.animate({ left: '-' + Math.floor(viewport.width())/3 + 'px' }, 400);
}
if (selfPosLeft < Math.floor(viewport.width())/3) {
itemList.animate({ left: Math.floor(viewport.width())/3 + 'px' }, 400);
}
});
CSS:
#wrapper {
width: 500px;
margin: 20px auto;
}
#carousel {
position: relative;
}
.viewport {
width: 260px;
border: 1px solid #6e6e6e;
height: 80px;
overflow: hidden;
position: relative;
margin-left: 100px;
}
.prev, .next {
position: absolute;
}
.prev {
top: 20px;
left: 0;
}
.next {
top: 20px;
right: 0;
}
.viewport ul {
position: absolute;
}
.viewport li {
float: left;
margin-right: 10px;
}
.viewport li a {
display: block;
width: 80px;
height: 80px;
background: #ddd;
}
While you have prepared all the information needed about all items, you can calculate the value of the left based on the clicked item.
Here is my modification:
and I've bound the click action of carousel items with this function and passed the clicked item using the self keyword.
var itemClicked=function(item){
var itemIndex=$(item).index(),
newLeft=(itemIndex*itemWidth*-1)+Math.floor(($(viewport).width()/itemWidth)/2)*itemWidth;
$(itemList).animate({left:newLeft+"px"},400);
};
You can check it working on this url: http://jsfiddle.net/rUZHg/3/
I assume that this should work despite of the number of viewed elements while it calculates the padding between the left 0 and the left of the center element.
Alright, it's ugly, I hope it gives you some ideas.
I created a global currentItem that tracks what's in the center. Every time the carousel moves this is updated.
The very useful variable I found was selfPosLeft which told me what was being clicked. I should add that 90 was the multiple I got from clicking around. Must be linked to your CSS and I don't know how to find this number dynamically.
Please try it :) http://jsfiddle.net/sp9Jv/4/
Well, I'm picturing that when you have more than 3 items you can change the code to compute the difference between the current item and the selfPosLeft of the clicked one, I'll leave that to you :) Like this, seems to work. http://jsfiddle.net/sp9Jv/5/