requestAnimationFrame with multiple independent objects - javascript

I am attempting to animate two different objects, a div formatted to look like a square and another formatted to look like a circle. I have a button for each object to start the animation which consists of just moving the object from left to right. I have included the code below. The issue I am having is that if I click on the Move Square button and then click on the Move Circle button, the square moves back to the left. What I am attempting to do is to move the objects independently of one another.
I am sure there is an object oriented solution for this but I have searched and have not found anything that makes sense to me. Any suggestions?
$(document).ready(function() {
var moveSquare = $('#moveSquare');
var moveCircle = $('#moveCircle');
var square = $('#square');
var squareText = $('#squareText');
square.css({
top: '100px',
left: '0px',
color: 'white',
position: 'fixed',
'text-align': 'center'
});
var pos_square = square.position();
squareText.html(pos_square.top + 'px' + '<br/>' + pos_square.left + 'px');
var circle = $('#circle');
var circleText = $('#circleText');
circle.css({
top: '300px',
left: '0px',
color: 'white',
position: 'fixed',
'text-align': 'center'
});
var pos_circle = circle.position();
circleText.html(pos_circle.top + 'px' + '<br/>' + pos_circle.left + 'px');
moveSquare.on('click', function() {
console.log('movesuqare here');
requestAnimationFrame(function(timestamp) {
starttime = timestamp;
move(timestamp, square, squareText, 800, 5000);
});
});
moveCircle.on('click', function() {
console.log('movecircle here');
requestAnimationFrame(function(timestamp) {
starttime = timestamp;
move(timestamp, circle, circleText, 800, 1000);
});
});
function move(timestamp, element, elementText, distance, duration) {
var runtime = timestamp - starttime;
var progress = runtime / duration;
progress = Math.min(progress, 1);
var leftPos = (distance * progress).toFixed(0) + 'px';
element.css({
left: leftPos,
position: 'absolute'
});
element.css({
'text-align': 'center'
});
var topPos = element.css('top') + '<br/>';
elementText.html(topPos + leftPos);
console.log(element.prop('id') + leftPos);
if (runtime < duration) {
requestAnimationFrame(function(timestamp) {
move(timestamp, element, elementText, distance, duration);
});
}
}
});
html {
position: fixed;
top: 0;
bottom: 0;
right: 0;
left: 0;
}
body {
font-family: 'Courier New';
color: black;
font-size: 15px;
width: auto;
top: 0;
bottom: 0;
right: 0;
left: 0;
}
.container {
width: 100px;
height: 100px;
}
.square_css {
width: 100px;
height: 100px;
background-color: blue;
}
.circle_css {
width: 100px;
height: 100px;
border-radius: 50%;
background-color: green;
}
.shapeText {
padding-top: 30%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="<?php echo URL; ?>views/index/css/index_Main.css" />
</head>
<body>
<div>
<input type="button" id="moveSquare" value="Move Square" />
</div>
<div>
<input type="button" id="moveCircle" value="Move Circle" />
</div>
<div id="square" class="square_css">
<div id="squareText" class="shapeText"></div>
</div>
<div id="circle" class="circle_css">
<div id="circleText" class="shapeText"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="<?php echo URL; ?>views/index/js/index_main.js"></script>
</body>
</html>

The problems is caused by the two animations sharing a common variable starttime.
To fix, you need some way of each animation having its own starttime.
There's a number of ways you could do that, the simplest of which is to pass a start time to move() along with the other parameters, from the click handlers. And because move() calls itself, starttime needs to be passed on to the next call.
$(document).ready(function() {
var square = $('#square').css({
'top': '100px',
'left': '0px',
'color': 'white',
'position': 'fixed',
'text-align': 'center'
});
var circle = $('#circle').css({
'top': '300px',
'left': '0px',
'color': 'white',
'position': 'fixed',
'text-align': 'center'
});
var squareText = $('#squareText');
var circleText = $('#circleText');
var pos_square = square.position();
var pos_circle = circle.position();
squareText.html(pos_square.top + 'px' + '<br/>' + pos_square.left + 'px');
circleText.html(pos_circle.top + 'px' + '<br/>' + pos_circle.left + 'px');
$('#moveSquare').on('click', function() { // button
console.log('movesuqare here');
requestAnimationFrame(function(timestamp) {
move(timestamp, timestamp, square, squareText, 800, 5000);
});
});
$('#moveCircle').on('click', function() { // button
console.log('movecircle here');
requestAnimationFrame(function(timestamp) {
move(timestamp, timestamp, circle, circleText, 800, 1000);
});
});
function move(starttime, timestamp, element, elementText, distance, duration) {
var runtime = timestamp - starttime;
var progress = runtime / duration;
progress = Math.min(progress, 1);
var leftPos = (distance * progress).toFixed(0) + 'px';
element.css({
left: leftPos,
position: 'absolute'
});
element.css({
'text-align': 'center'
});
var topPos = element.css('top') + '<br/>';
elementText.html(topPos + leftPos);
console.log(element.prop('id') + leftPos);
if (runtime < duration) {
requestAnimationFrame(function(timestamp) {
move(starttime, timestamp, element, elementText, distance, duration);
});
}
}
});
html {
position: fixed;
top: 0;
bottom: 0;
right: 0;
left: 0;
}
body {
font-family: 'Courier New';
color: black;
font-size: 15px;
width: auto;
top: 0;
bottom: 0;
right: 0;
left: 0;
}
.container {
width: 100px;
height: 100px;
}
.square_css {
width: 100px;
height: 100px;
background-color: blue;
}
.circle_css {
width: 100px;
height: 100px;
border-radius: 50%;
background-color: green;
}
.shapeText {
padding-top: 30%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="<?php echo URL; ?>views/index/css/index_Main.css" />
</head>
<body>
<div>
<input type="button" id="moveSquare" value="Move Square" />
</div>
<div>
<input type="button" id="moveCircle" value="Move Circle" />
</div>
<div id="square" class="square_css">
<div id="squareText" class="shapeText"></div>
</div>
<div id="circle" class="circle_css">
<div id="circleText" class="shapeText"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="<?php echo URL; ?>views/index/js/index_main.js"></script>
</body>
</html>

Related

Javascript carosel animation

I'm trying to make an image carousel with center animation. I don't want to use CSS animations, instead I'd like to use jQuery.
By pressing the 'Prev' button the animation will start. One of the slides which will be central begins to grow. I've used jQuery's animate() to animate width and height. Everything works as required except I can't understand why the animation makes the central slide jump.
I have created this sample. If you push the 'Prev' button the animation will start.
var scroll_speed = 4000;
var items_cnt = $('.mg_item').length;
var container_size = $(".main_cnt").innerWidth();
var item_avg_w = container_size / 5;
var item_center_w = ((item_avg_w / 100) * 20) + item_avg_w;
var item_center_h = (item_center_w / 16) * 9 + 30;
var item_w = ((container_size - item_center_w) / 4) - 2;
var item_h = ((item_w / 16) * 9);
var gallery_content = $('.gallery_body').html();
$('.gallery_body').html(gallery_content + gallery_content + gallery_content);
var items_offset = items_cnt * item_w + 14;
$('.gallery_body').css('left', -items_offset);
$('.mg_item').css("width", item_w);
$('.mg_item').css("height", item_h);
//$('.mg_item').css("margin-bottom", (item_center_h - item_h) / 2);
//$('.mg_item').css("margin-top", (item_center_h - item_h) / 2);
//$('.mg_item_с').css("width", item_center_w);
//$('.mg_item_с').css("height", item_center_h);
//document.documentElement.style.setProperty('--center_width', item_center_w + "px");
//document.documentElement.style.setProperty('--center_height', item_center_h + "px");
$('.main_cnt').css("height", item_center_h);
check_visible();
AssignCenter(0);
function gonext() {
AssignCenter(-1);
ZoomIn();
$('.gallery_body').animate({
left: '+=' + (item_w + 2),
}, scroll_speed, "linear", function() {
LoopSlides();
});
}
function goprev() {
AssignCenter(1);
ZoomIn();
$('.gallery_body').animate({
left: '-=' + (item_w + 2),
}, scroll_speed, "linear", function() {
LoopSlides();
});
}
function ZoomIn() {
$('.center').animate({
width: item_center_w + 'px',
height: item_center_h + 'px',
}, scroll_speed, function() {});
}
function LoopSlides() {
var cur_pos = $('.gallery_body').position().left
var left_margin = Math.abs(items_offset * 2 - item_w) * -1;
var right_margin = 0 - item_w;
if (cur_pos < left_margin) {
$('.gallery_body').css('left', -items_offset);
}
if (cur_pos >= 0) {
$('.gallery_body').css('left', -items_offset);
}
check_visible();
AssignCenter(0);
}
function check_visible() {
$('.mg_item').each(function(i, obj) {
var pos = $(this).offset().left;
if (pos < 0 || pos > container_size) {
$(this).addClass("invisible");
$(this).removeClass("active");
} else {
$(this).addClass("active");
$(this).removeClass("invisible");
}
});
}
function AssignCenter(offset) {
var center_slide = $('.active')[2 + offset];
$('.center').each(function(i, obj) {
$(this).removeClass("center");
});
$(center_slide).addClass("center");
//$(center_slide).css("width", item_center_w);
//$(center_slide).css("height", item_center_h);
}
:root {
--center_width: 0px;
--center_height: 0px;
}
.main_cnt {
background-color: rgb(255, 0, 0);
padding: 0px;
overflow: hidden;
margin: 0px;
}
.gallery_body {
width: 500%;
background-color: rgb(128, 128, 128);
position: relative;
}
.mg_item {
width: 198px;
height: 150px;
background-color: blue;
display: inline-block;
position: relative;
margin: -1px;
padding: 0px;
font-size: 120px;
}
.center {
background-color: brown;
/*width: var(--center_width) !important;
height: var(--center_height) !important;*/
}
.item_c {
width: 410px;
height: 150px;
background-color: blueviolet;
display: inline-block;
position: relative;
margin: -1px;
padding: 0px;
font-size: 120px;
}
.video-js .vjs-dock-text {
text-align: right;
}
<script src="https://code.jquery.com/jquery-2.2.0.min.js" type="text/javascript"></script>
<div class="main_cnt">
<div class="gallery_body">
<div class="mg_item">1</div>
<div class="mg_item">2</div>
<div class="mg_item">3</div>
<div class="mg_item">4</div>
<div class="mg_item">5</div>
<div class="mg_item">6</div>
<div class="mg_item">7</div>
</div>
</div>
<br><br>
<button onclick="gonext()">GONEXT</button>
<button onclick="goprev()">GOPREV</button>
<button onclick="check_visible()">CHEVIS</button>

How to rotate a pie chart by progressbar plugin counterclockwise?

I use an open-source plugin in github, here is the link:
https://github.com/yxfanxiao/jQuery-plugin-progressbar
Please see the codes below:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Progress Bar</title>
<link rel="stylesheet" href="jQuery-plugin-progressbar.css">
<script src="jquery-1.11.3.js"></script>
<script src="jQuery-plugin-progressbar.js"></script>
</head>
<body>
<div class="progress-bar position"></div>
<div class="progress-bar position" data-percent="60" data-duration="1000" data-color="#ccc,yellow"></div>
<div class="progress-bar position" data-percent="20" data-color="#a456b1,#12b321"></div>
<input type="submit" value="加载">
<script>
$(".progress-bar").loading();
$('input').on('click', function () {
$(".progress-bar").loading();
});
</script>
</body>
</html>
JS:
;
(function ($) {
$.fn.loading = function () {
var DEFAULTS = {
backgroundColor: '#b3cef6',
progressColor: '#4b86db',
percent: 75,
duration: 2000
};
$(this).each(function () {
var $target = $(this);
var opts = {
backgroundColor: $target.data('color') ? $target.data('color').split(',')[0] : DEFAULTS.backgroundColor,
progressColor: $target.data('color') ? $target.data('color').split(',')[1] : DEFAULTS.progressColor,
percent: $target.data('percent') ? $target.data('percent') : DEFAULTS.percent,
duration: $target.data('duration') ? $target.data('duration') : DEFAULTS.duration
};
// console.log(opts);
$target.append('<div class="background"></div><div class="rotate"></div><div class="left"></div><div class="right"></div><div class=""><span>' + opts.percent + '%</span></div>');
$target.find('.background').css('background-color', opts.backgroundColor);
$target.find('.left').css('background-color', opts.backgroundColor);
$target.find('.rotate').css('background-color', opts.progressColor);
$target.find('.right').css('background-color', opts.progressColor);
var $rotate = $target.find('.rotate');
setTimeout(function () {
$rotate.css({
'transition': 'transform ' + opts.duration + 'ms linear',
'transform': 'rotate(' + opts.percent * 3.6 + 'deg)'
});
},1);
if (opts.percent > 50) {
var animationRight = 'toggle ' + (opts.duration / opts.percent * 50) + 'ms step-end';
var animationLeft = 'toggle ' + (opts.duration / opts.percent * 50) + 'ms step-start';
$target.find('.right').css({
animation: animationRight,
opacity: 1
});
$target.find('.left').css({
animation: animationLeft,
opacity: 0
});
}
});
}
})(jQuery);
CSS:
.position {
float: left;
margin: 100px 50px;
}
.progress-bar {
position: relative;
height: 100px;
width: 100px;
}
.progress-bar div {
position: absolute;
height: 100px;
width: 100px;
border-radius: 50%;
}
.progress-bar div span {
position: absolute;
font-family: Arial;
font-size: 25px;
line-height: 75px;
height: 75px;
width: 75px;
left: 12.5px;
top: 12.5px;
text-align: center;
border-radius: 50%;
background-color: white;
}
.progress-bar .background {
background-color: #b3cef6;
}
.progress-bar .rotate {
clip: rect(0 50px 100px 0);
background-color: #4b86db;
}
.progress-bar .left {
clip: rect(0 50px 100px 0);
opacity: 1;
background-color: #b3cef6;
}
.progress-bar .right {
clip: rect(0 50px 100px 0);
transform: rotate(180deg);
opacity: 0;
background-color: #4b86db;
}
#keyframes toggle {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
Note that you can download a zip-file from the link provided including those codes. As to be seen, originally the pie charts are rotating clockwise. All I need is to make them rotate counterclockwise. That was looking easy but I could not manage to do it for hours unfortunately. Any help or advise would be so appreciated! Thanks!!
Edit: Please note that the starting point (origin) of the animation should not be changed, should start from the top (north).
You should start by multiplying your rotate value by its minus value; -3.6 instead of 3.6. You'd also have to update the CSS accordingly as otherwise it will start animating from bottom contrary to original version where it starts from top.
You can trick it via swapping left and right components, but that will affect the progress values less than 50%, thus you should add an else statement to handle that as well.
Hence final JS file becomes like below;
JS:
;
(function ($) {
$.fn.loading = function () {
var DEFAULTS = {
backgroundColor: '#f00',
progressColor: '#adadad',
percent: 75,
duration: 2000
};
$(this).each(function () {
var $target = $(this);
var opts = {
backgroundColor: $target.data('color') ? $target.data('color').split(',')[0] : DEFAULTS.backgroundColor,
progressColor: $target.data('color') ? $target.data('color').split(',')[1] : DEFAULTS.progressColor,
percent: $target.data('percent') ? $target.data('percent') : DEFAULTS.percent,
duration: $target.data('duration') ? $target.data('duration') : DEFAULTS.duration
};
$target.append('<div class="background"></div><div class="rotate"></div>'+
'<div class="left"></div>'+
'<div class="right"></div><div class=""><span>' +
+ opts.percent + '%</span></div>');
$target.find('.background').css('background-color', opts.backgroundColor);
$target.find('.left').css('background-color', opts.backgroundColor);
$target.find('.rotate').css('background-color', opts.progressColor);
$target.find('.right').css('background-color', opts.progressColor);
var $rotate = $target.find('.rotate');
setTimeout(function () {
$rotate.css({
'transition': 'transform ' + opts.duration + 'ms linear',
'transform': 'rotateZ(' + -opts.percent * 3.6 + 'deg)'
});
},1);
if (opts.percent > 50) {
var animationRight = 'toggle ' + (opts.duration / opts.percent * 50) + 'ms step-end';
var animationLeft = 'toggle ' + (opts.duration / opts.percent * 50) + 'ms step-start';
$target.find('.left').css({
animation: animationRight,
opacity: 1
});
$target.find('.right').css({
animation: animationLeft,
opacity: 0
});
}
else {
var animationRight = 'toggle ' + (opts.duration / opts.percent * 50) + 'ms step-end';
var animationLeft = 'toggle ' + (opts.duration / opts.percent * 50) + 'ms step-start';
$target.find('.left').css({
animation: animationRight,
opacity: 0
});
$target.find('.right').css({
animation: animationLeft,
opacity: 1
});
}
});
}
})(jQuery);

show moving image form one div to other div in javascript or jquery

When I click on image it will go in other div but when it goes in other div it should be display moving image from div A to div B
Can any one tried this ?
I did this just for fun: fiddle
HTML
<div class="blue">
<img src="http://fakeimg.pl/200/" class="move-me" />
<img src="http://fakeimg.pl/200/" class="move-me" />
<img src="http://fakeimg.pl/200/" class="move-me" />
</div>
<div class="green"></div>
jQuery
$(document).on('click', '.move-me', function(){
var $img = $(this);
var x1 = $img.position().left;
var y1 = $img.position().top;
var $imgCloned1 = $img.clone().css("visibility", "hidden");
var $imgCloned2 = $imgCloned1.clone();
$imgCloned2.insertAfter($img);
$(".green").append($img);
var x2 = $img.position().left;
var y2 = $img.position().top;
$img.css({'position':'absolute', 'left': x1 + 'px', 'top': y1 + 'px'});
$imgCloned1.appendTo(".green");
$img.animate({'left': x2, 'top': y2 + 'px'}, 1000, function() {
$img.css({'position':'', 'left': '', 'top': ''});
$img.removeClass("move-me");
$imgCloned1.remove();
$imgCloned2.remove();
});
});
CSS
.blue, .green {
min-height: 200px;
margin: 30px
}
.blue {
background: skyblue;
}
.green {
background: lightgreen;
}
You can use the following script in order to move one image from one position to another based on the position of a "target" div.
When you click on the image, image move to "target" div.
When click on yellow box, you can change position of "target" div and on click on image you can preposition image again.
(function(window) {
var _app = {
elmImage: null,
elmTarget: null,
imageGeometry: null,
targetGeometry: null,
getDomImage: function() {
this.elmImage = document.getElementById('image');
},
getDomSourceGeometry: function() {
this.imageGeometry = this.elmImage.getBoundingClientRect();
},
getDomtarget: function() {
this.elmTarget = document.getElementById('target');
},
getDomTargetGeometry: function() {
this.targetGeometry = this.elmTarget.getBoundingClientRect();
},
animate: function() {
var top = this.targetGeometry.top + 'px',
left = this.targetGeometry.left + 'px';
$(this.elmImage).animate({
top: top,
left: left
});
},
listenImageClick: function() {
$(this.elmImage).click(function() {
_app.animate();
});
},
listenChangeTarget: function() {
$('#targetChange').click(function() {
this.changeTargetPosition();
}.bind(this));
},
changeTargetPosition: function() {
$(this.elmTarget).css({
top: '100px',
left: '50px'
});
this.logic();
},
logic: function() {
_app.getDomImage();
_app.getDomSourceGeometry();
_app.getDomtarget();
_app.getDomTargetGeometry();
}
};
this.elmImage = null;
$(document).ready(function() {
_app.logic();
_app.listenImageClick();
_app.listenChangeTarget();
});
})(window);
#target {
position: absolute;
top: 300px;
left: 300px;
width: 200px;
height: 200px;
background-color: darkgray;
}
#image {
position: absolute;
width: 200px;
height: 200px;
}
#targetChange {
position: absolute;
top: 0;
left: 300px;
width: 300px;
height: 20px;
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="target"></div>
<img id="image" src="http://lorempixel.com/200/200/" alt="Smiley face" height="42" width="42">
<div id="targetChange"> Click here to change position target div</div>

How can I drag a div and keep the cursor on the same spot as I clicked it at?

I'm trying to drag a div when I click on it but when I do it the div blinks and moves to the left, if I remove offset and put position instead it works but the cursor goes to the left top of the div.
var selected = 0,
x = 0,
y = 0;
$.fn.isDraggable = function() {
$(this).on('mousedown', function(e) {
selected = $(this);
$(selected).css({
position: 'absolute',
left: e.pageX - $(selected).position().left,
top: e.pageY - $(selected).position().top
});
});
$(document).on('mouseup', function() {
if (selected !== 0) {
selected = 0;
}
});
$(document).bind('mousemove', function(e) {
$(selected).css({
position: 'absolute',
left: e.pageX - $(selected).offset().left,
top: e.pageY - $(selected).offset().top
});
});
return true;
};
$('#card').isDraggable();
#card {
position: fixed;
width: 100px;
height: 150px;
top: calc(50% - 75px);
left: calc(50% - 50px);
border: 1px solid #D3D3D3;
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<title>freeMarketRocks</title>
</head>
<body>
<div>
<div id="card">
</div>
</div>
</body>
</html>
You have 2 problems here. First your event handler logic might result in a performance waste as you are asking your browser to constantly check for mouse movement, even if its not necessary.
Second, the calculation of the box coordiante is wrong, it must take the initial position in account. That's the purpose of my deltaX and deltaY variables in the fiddle
Here's a working fiddle https://jsfiddle.net/TCHdevlp/t2bapq5y/
Or Here:
var selected = 0,
x = 0,
y = 0,
boxX = 0,
boxY = 0;
$.fn.isDraggable = function() {
$(this).on('mousedown', function(e) {
selected = $(this);
//get initial positions
x = e.pageX;
y = e.pageY;
BoxX = $(selected).offset().left;
BoxY = $(selected).offset().top;
//bind mousemove
$(document).bind('mousemove', function(e) {
//compute new coordinate
deltaX = e.pageX - x;
deltaY = e.pageY - y;
$(selected).css({
position: 'absolute',
left: (BoxX + deltaX),
top: (BoxY + deltaY)
});
});
});
//unbind when finished
$(document).on('mouseup', function() {
if (selected !== 0) {
$(document).unbind("mousemove");
selected = 0;
}
});
return true;
};
$('#card').isDraggable();
#card {
position: fixed;
width: 100px;
height: 150px;
top: 10x;
left: 10px;
border: 1px solid #D3D3D3;
}
<div>
<div id="card">
</div>
</div>
var selected = 0,
x = 0,
y = 0;
$.fn.isDraggable = function() {
var moveFrame, comStartX, comStartY, startMousePosX, startMousePosY;
$(this).on('mousedown', function(e) {
selected = $(this);
moveFrame = true;
comStartX = $(this).position().left;
comStartY = $(this).position().top;
startMousePosX = e.pageX;
startMousePosY = e.pageY;
});
$(document).on('mouseup', function() {
moveFrame = false;
});
$(document).bind('mousemove', function(e) {
if (moveFrame){
currPosX = comStartX + (e.pageX - startMousePosX);
currPosY = comStartY + (e.pageY - startMousePosY);
$(selected).css({position: 'absolute', 'left': currPosX + 'px', 'top': currPosY + 'px'});
}
});
return true;
};
$('#card').isDraggable();
#card {
position: fixed;
width: 100px;
height: 150px;
top: calc(50% - 75px);
left: calc(50% - 50px);
border: 1px solid #D3D3D3;
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<title>freeMarketRocks</title>
</head>
<body>
<div>
<div id="card">
</div>
</div>
</body>
</html>

Multiple sliders on one page

Ok, I builded a slider in javascript and Jquery (with help of you guys) But now I want to have multiple sliders on 1 page. While using just one javascript. BUT...the slider can be different in width (or number of items): also the name of the slider is different because of the css width.
So How do I use 1 javascript to controle different sliders
Here is my code:
HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<style type="text/css">
#temp{
height: 300px;
}
#container{
width: 500px;
height: 150px;
background:#CDFAA8;
overflow:hidden;
position:absolute;
left: 13px;
}
#slider{
width: 800px;
height: 150px;
background:#063;
position:absolute;
left: 0px;
}
#block1{
width: 100px;
height: 150px;
background:#067;
float: left;
}
#block2{
width: 100px;
height: 150px;
background:#079;
float: left;
}
#move_right{
height: 150px;
width: 20px;
background: #3f3f3f;
position: absolute;
right:0px;
z-index: 200;
opacity: 0.2;
}
#move_left{
height: 150px;
width: 20px;
background: #3f3f3f;
position: absolute;
left:0px;
z-index: 200;
opacity: 0.2;
}​
</style>
</head>
<body>
<div id="temp">
<div id="container">
<div id="move_left"><button id="right">«</button></div><div id="move_right"><br><br><button id="left">»</button></div>
<div id="slider">
<div id="block1">1</div>
<div id="block2">2</div>
<div id="block1">3</div>
<div id="block2">4</div>
<div id="block1">5</div>
<div id="block2">6</div>
<div id="block1">7</div>
<div id="block2">8</div>
</div>
</div>
</div>
<div id="slider">
<div id="block1">1</div>
<div id="block2">2</div>
<div id="block1">3</div>
<div id="block2">4</div>
<div id="block1">5</div>
<div id="block2">6</div>
<div id="block1">7</div>
<div id="block2">8</div>
</div>
</div>
</div>
JavaScript
(function($) {
var slider = $('#slider'),
step = 500,
left = parseInt(slider.css('left'), 10),
max = $('#container').width() - slider.width(),
min = 0;
$("#left").click(function() {
if (left > max) {
var newLeft = left - step;
left = (newLeft>max) ? newLeft : max;
$("#slider").animate({
"left": left + 'px'
}, "slow");
}
});
$("#right").click(function() {
if (left < 0) {
var newLeft = left + step;
left = (newLeft<min) ? newLeft : min;
slider.animate({
"left": left + 'px'
}, "slow");
}
});
})(jQuery);
This should be fine:
(function($) {
$('#temp #container').each(function(){
var slider = $(this).find('#slider'),
parent = $(this),
step = 500,
left = parseInt(slider.css('left'), 10),
max = parent.width() - slider.width(),
min = 0;
parent.find("#left").click(function() {
if (left > max) {
var newLeft = left - step;
left = (newLeft>max) ? newLeft : max;
slider.animate({
"left": left + 'px'
}, "slow");
}
});
parent.find("#right").click(function() {
if (left < 0) {
var newLeft = left + step;
left = (newLeft<min) ? newLeft : min;
slider.animate({
"left": left + 'px'
}, "slow");
}
});
});
})(jQuery);​
FIDDLE
In theory you could do some code which can take a selector to a wrapper element (which has the required slider elements inside) as some parameter. And then you can from this element create selectors which are more dynamic. I'm not sure where you get "step = 500" from, but that's maybe something you could grab dynamically from some relevant element.

Categories

Resources