Related
Im making a multiplayer endless runner game and want to make the background move down in a loop with random obstacles in my way. So far I was able to make the scene with controls for the player, have set up a multiplayer aspect, and a sign in. However, I am not able to figure out how to set the background in a loop or add obstacles moving towards the player.
Heres the code:
App2.JS:
var mongojs = require("mongojs");
var db = mongojs('localhost:27017/myGame', ['account','progress']);
var express = require('express');
var app = express();
var serv = require('http').Server(app);
app.get('/',function(req, res) {
res.sendFile(__dirname + '/client/index2.html');
});
app.use('/client',express.static(__dirname + '/client'));
serv.listen(2000);
console.log("Server started.");
var SOCKET_LIST = {};
var Entity = function(){
var self = {
x:250,
y:250,
spdX:0,
spdY:0,
id:"",
}
self.update = function(){
self.updatePosition();
}
self.updatePosition = function(){
self.x += self.spdX;
self.y += self.spdY;
}
self.getDistance = function(pt){
return Math.sqrt(Math.pow(self.x-pt.x,2) + Math.pow(self.y-pt.y,2));
}
return self;
}
var Player = function(id){
var self = Entity();
self.id = id;
self.number = "" + Math.floor(10 * Math.random());
self.pressingRight = false;
self.pressingLeft = false;
self.pressingUp = false;
self.pressingDown = false;
self.pressingAttack = false;
self.mouseAngle = 0;
self.maxSpd = 25;
self.hp = 10;
self.hpMax = 10;
self.score = 0;
var super_update = self.update;
self.update = function(){
self.updateSpd();
super_update();
if(self.pressingAttack){
self.shootBullet(self.mouseAngle);
}
}
self.shootBullet = function(angle){
var b = Bullet(self.id,angle);
b.x = self.x;
b.y = self.y;
}
self.updateSpd = function(){
if(self.pressingRight && (self.x + 30) < 500)
self.spdX = self.maxSpd;
else if(self.pressingLeft && self.x > 0)
self.spdX = -self.maxSpd;
else
self.spdX = 0;
if(self.pressingUp)
self.spdY = 0;
else if(self.pressingDown)
self.spdY = 0;
else
self.spdY = 0;
}
self.getInitPack = function(){
return {
id:self.id,
x:self.x,
y:self.y,
number:self.number,
hp:self.hp,
hpMax:self.hpMax,
score:self.score,
};
}
self.getUpdatePack = function(){
return {
id:self.id,
x:self.x,
y:self.y,
hp:self.hp,
score:self.score,
}
}
Player.list[id] = self;
initPack.player.push(self.getInitPack());
return self;
}
Player.list = {};
Player.onConnect = function(socket){
var player = Player(socket.id);
socket.on('keyPress',function(data){
if(data.inputId === 'left')
player.pressingLeft = data.state;
else if(data.inputId === 'right')
player.pressingRight = data.state;
else if(data.inputId === 'up')
player.pressingUp = data.state;
else if(data.inputId === 'down')
player.pressingDown = data.state;
else if(data.inputId === 'attack')
player.pressingAttack = data.state;
else if(data.inputId === 'mouseAngle')
player.mouseAngle = data.state;
});
socket.emit('init',{
selfId:socket.id,
player:Player.getAllInitPack(),
bullet:Bullet.getAllInitPack(),
})
}
Player.getAllInitPack = function(){
var players = [];
for(var i in Player.list)
players.push(Player.list[i].getInitPack());
return players;
}
Player.onDisconnect = function(socket){
delete Player.list[socket.id];
removePack.player.push(socket.id);
}
Player.update = function(){
var pack = [];
for(var i in Player.list){
var player = Player.list[i];
player.update();
pack.push(player.getUpdatePack());
}
return pack;
}
var Bullet = function(parent,angle){
var self = Entity();
self.id = Math.random();
self.spdX = Math.cos(angle/180*Math.PI) * 10;
self.spdY = Math.sin(angle/180*Math.PI) * 10;
self.parent = parent;
self.timer = 0;
self.toRemove = false;
var super_update = self.update;
self.update = function(){
if(self.timer++ > 100)
self.toRemove = true;
super_update();
for(var i in Player.list){
var p = Player.list[i];
if(self.getDistance(p) < 32 && self.parent !== p.id){
p.hp -= 1;
if(p.hp <= 0){
var shooter = Player.list[self.parent];
if(shooter)
shooter.score += 1;
p.hp = p.hpMax;
p.x = Math.random() * 500;
p.y = Math.random() * 500;
}
self.toRemove = true;
}
}
}
self.getInitPack = function(){
return {
id:self.id,
x:self.x,
y:self.y,
};
}
self.getUpdatePack = function(){
return {
id:self.id,
x:self.x,
y:self.y,
};
}
Bullet.list[self.id] = self;
initPack.bullet.push(self.getInitPack());
return self;
}
Bullet.list = {};
Bullet.update = function(){
var pack = [];
for(var i in Bullet.list){
var bullet = Bullet.list[i];
bullet.update();
if(bullet.toRemove){
delete Bullet.list[i];
removePack.bullet.push(bullet.id);
} else
pack.push(bullet.getUpdatePack());
}
return pack;
}
Bullet.getAllInitPack = function(){
var bullets = [];
for(var i in Bullet.list)
bullets.push(Bullet.list[i].getInitPack());
return bullets;
}
var DEBUG = true;
var isValidPassword = function(data,cb){
db.account.find({username:data.username,password:data.password},function(err,res){
if(res.length > 0)
cb(true);
else
cb(false);
});
}
var isUsernameTaken = function(data,cb){
db.account.find({username:data.username},function(err,res){
if(res.length > 0)
cb(true);
else
cb(false);
});
}
var addUser = function(data,cb){
db.account.insert({username:data.username,password:data.password},function(err){
cb();
});
}
var io = require('socket.io')(serv,{});
io.sockets.on('connection', function(socket){
socket.id = Math.random();
SOCKET_LIST[socket.id] = socket;
socket.on('signIn',function(data){
isValidPassword(data,function(res){
if(res){
Player.onConnect(socket);
socket.emit('signInResponse',{success:true});
} else {
socket.emit('signInResponse',{success:false});
}
});
});
socket.on('signUp',function(data){
isUsernameTaken(data,function(res){
if(res){
socket.emit('signUpResponse',{success:false});
} else {
addUser(data,function(){
socket.emit('signUpResponse',{success:true});
});
}
});
});
socket.on('disconnect',function(){
delete SOCKET_LIST[socket.id];
Player.onDisconnect(socket);
});
socket.on('sendMsgToServer',function(data){
var playerName = ("" + socket.id).slice(2,7);
for(var i in SOCKET_LIST){
SOCKET_LIST[i].emit('addToChat',playerName + ': ' + data);
}
});
socket.on('evalServer',function(data){
if(!DEBUG)
return;
var res = eval(data);
socket.emit('evalAnswer',res);
});
});
var initPack = {player:[],bullet:[]};
var removePack = {player:[],bullet:[]};
setInterval(function(){
var pack = {
player:Player.update(),
bullet:Bullet.update(),
}
for(var i in SOCKET_LIST){
var socket = SOCKET_LIST[i];
socket.emit('init',initPack);
socket.emit('update',pack);
socket.emit('remove',removePack);
}
initPack.player = [];
initPack.bullet = [];
removePack.player = [];
removePack.bullet = [];
},1000/25);
indexCars2.html:
<div id="signDiv">
Username: <input id="signDiv-username" type="text"></input><br>
Password: <input id="signDiv-password" type="password"></input>
<button id="signDiv-signIn">Sign In</button>
<button id="signDiv-signUp">Sign Up</button>
</div>
<div id="animate"
style = "position: relative;"
style = "border: 1px solid green;"
style = "background: yellow; "
style = "width: 100;"
style = "height: 100;"
style = "z-index: 5;">
Sample
</div>
<div id="gameDiv" style="display:none;">
<canvas id="ctx" width="500" height="500" style="border:1px solid #000000;"></canvas>
<div id="chat-text" style="width:500px;height:100px;overflow-y:scroll">
<div>Hello!</div>
</div>
<form id="chat-form">
<input id="chat-input" type="text" style="width:500px"></input>
</form>
</div>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
$(document).ready(function(e) {
var width = "+=" + $(document).width();
$("#animate").animate({
left: width
}, 5000, function() {
// Animation complete.
});
});</script>
<script>
// var WIDTH = 500;
// var HEIGHT = 500;
var socket = io();
//sign
var signDiv = document.getElementById('signDiv');
var signDivUsername = document.getElementById('signDiv-username');
var signDivSignIn = document.getElementById('signDiv-signIn');
var signDivSignUp = document.getElementById('signDiv-signUp');
var signDivPassword = document.getElementById('signDiv-password');
signDivSignIn.onclick = function(){
socket.emit('signIn',{username:signDivUsername.value,password:signDivPassword.value});
}
signDivSignUp.onclick = function(){
socket.emit('signUp',{username:signDivUsername.value,password:signDivPassword.value});
}
socket.on('signInResponse',function(data){
if(data.success){
signDiv.style.display = 'none';
gameDiv.style.display = 'inline-block';
} else
alert("Sign in unsuccessul.");
});
socket.on('signUpResponse',function(data){
if(data.success){
alert("Sign up successul.");
} else
alert("Sign up unsuccessul.");
});
//chat
var chatText = document.getElementById('chat-text');
var chatInput = document.getElementById('chat-input');
var chatForm = document.getElementById('chat-form');
socket.on('addToChat',function(data){
chatText.innerHTML += '<div>' + data + '</div>';
});
socket.on('evalAnswer',function(data){
console.log(data);
});
chatForm.onsubmit = function(e){
e.preventDefault();
if(chatInput.value[0] === '/')
socket.emit('evalServer',chatInput.value.slice(1));
else
socket.emit('sendMsgToServer',chatInput.value);
chatInput.value = '';
}
//game
var Img = {};
Img.player = new Image();
Img.player.src = '/client/img/lamboS.png';
Img.bullet = new Image();
Img.bullet.src = '/client/img/bullet.png';
Img.map = new Image();
Img.map.src = '/client/img/road.png';
var ctx = document.getElementById("ctx").getContext("2d");
ctx.font = '30px Arial';
var Player = function(initPack){
var self = {};
self.id = initPack.id;
self.number = initPack.number;
self.x = initPack.x;
self.y = initPack.y;
self.hp = initPack.hp;
self.hpMax = initPack.hpMax;
self.score = initPack.score;
self.draw = function(){
// var x = self.x - Player.list[selfId].x + WIDTH/2;
// var y = self.y - Player.list[selfId].y + HEIGHT/2;
var hpWidth = 30 * self.hp / self.hpMax;
ctx.fillStyle = 'red';
ctx.fillRect(self.x - hpWidth/2,self.y - 40,hpWidth,4);
var width = Img.player.width;
var height = Img.player.height;
ctx.drawImage(Img.player,
0,0,Img.player.width,Img.player.height,
self.x-width/2,self.y-height/2,width,height);
//ctx.fillText(self.score,self.x,self.y-60);
}
Player.list[self.id] = self;
return self;
}
Player.list = {};
var Bullet = function(initPack){
var self = {};
self.id = initPack.id;
self.x = initPack.x;
self.y = initPack.y;
self.draw = function(){
var width = Img.bullet.width/2;
var height = Img.bullet.height/2;
// var x = self.x - Player.list[selfId].x + WIDTH/2;
// var y = self.y - Player.list[selfId].y + HEIGHT/2;
ctx.drawImage(Img.bullet,
0,0,Img.bullet.width,Img.bullet.height,
self.x-width/2,self.y-height/2,width,height);
}
Bullet.list[self.id] = self;
return self;
}
Bullet.list = {};
var selfId = null;
socket.on('init',function(data){
if(data.selfId)
selfId = data.selfId;
//{ player : [{id:123,number:'1',x:0,y:0},{id:1,number:'2',x:0,y:0}], bullet: []}
for(var i = 0 ; i < data.player.length; i++){
new Player(data.player[i]);
}
for(var i = 0 ; i < data.bullet.length; i++){
new Bullet(data.bullet[i]);
}
});
socket.on('update',function(data){
//{ player : [{id:123,x:0,y:0},{id:1,x:0,y:0}], bullet: []}
for(var i = 0 ; i < data.player.length; i++){
var pack = data.player[i];
var p = Player.list[pack.id];
if(p){
if(pack.x !== undefined)
p.x = pack.x;
if(pack.y !== undefined)
p.y = pack.y;
if(pack.hp !== undefined)
p.hp = pack.hp;
if(pack.score !== undefined)
p.score = pack.score;
}
}
for(var i = 0 ; i < data.bullet.length; i++){
var pack = data.bullet[i];
var b = Bullet.list[data.bullet[i].id];
if(b){
if(pack.x !== undefined)
b.x = pack.x;
if(pack.y !== undefined)
b.y = pack.y;
}
}
for(var i = 0 ; i < data.bullet.length; i++){
var pack = data.bullet[i];
var b = Bullet.list[data.bullet[i].id];
if(b){
if(pack.x !== undefined)
b.x = pack.x;
if(pack.y !== undefined)
b.y = pack.y;
}
}
});
socket.on('remove',function(data){
//{player:[12323],bullet:[12323,123123]}
for(var i = 0 ; i < data.player.length; i++){
delete Player.list[data.player[i]];
}
for(var i = 0 ; i < data.bullet.length; i++){
delete Bullet.list[data.bullet[i]];
}
});
setInterval(function(){
if(!selfId)
return;
ctx.clearRect(0,0,500,500);
drawMap();
drawScore();
for(var i in Player.list)
Player.list[i].draw();
for(var i in Bullet.list)
Bullet.list[i].draw();
},40);
var drawMap = function(){
var x = 0;
var y = 0;
// var x = WIDTH/2 - Player.list[selfId].x;
// var y = HEIGHT/2 - Player.list[selfId].y;
ctx.drawImage(Img.map, x, y);
// for(x = 0; x < 5; x += 100){
//// ctx.drawImage(Img.map, x, y);
// }
}
var drawScore = function(){
ctx.fillStyle = 'red';
ctx.fillText(Player.list[selfId].score,10,30);
}
document.onkeydown = function(event){
if(event.keyCode === 68) //d
socket.emit('keyPress',{inputId:'right',state:true});
else if(event.keyCode === 83) //s
socket.emit('keyPress',{inputId:'down',state:true});
else if(event.keyCode === 65) //a
socket.emit('keyPress',{inputId:'left',state:true});
else if(event.keyCode === 87) // w
socket.emit('keyPress',{inputId:'up',state:true});
}
document.onkeyup = function(event){
if(event.keyCode === 68) //d
socket.emit('keyPress',{inputId:'right',state:false});
else if(event.keyCode === 83) //s
socket.emit('keyPress',{inputId:'down',state:false});
else if(event.keyCode === 65) //a
socket.emit('keyPress',{inputId:'left',state:false});
else if(event.keyCode === 87) // w
socket.emit('keyPress',{inputId:'up',state:false});
}
document.onmousedown = function(event){
socket.emit('keyPress',{inputId:'attack',state:true});
}
document.onmouseup = function(event){
socket.emit('keyPress',{inputId:'attack',state:false});
}
document.onmousemove = function(event){
var x = -250 + event.clientX - 8;
var y = -250 + event.clientY - 8;
var angle = Math.atan2(y,x) / Math.PI * 180;
socket.emit('keyPress',{inputId:'mouseAngle',state:angle});
}
</script>
The idea in endless runners is to actually move the objects towards the player at constant speed(i.e. speed of the player). As soon as they get off the screen you can stop updating them. Check out this http://blog.sklambert.com/html5-game-tutorial-module-pattern/?utm_content=buffer18ac6&utm_medium=social&utm_source=twitter.com&utm_campaign=buffer
I really don't know how to get the following variable from a function into another function. I've read most of the articles and answers about that, and I think my example is more complex. Otherwise, I'm doing it wrong.
This is the function I'm using to determine the value of the wpbar variable. I even could start with $(document).ready(function(), but I removed it for the example:
function wp_adminbar() {
"use strict";
var win = $(window),
wpbar = 0;
if ($('body').hasClass('admin-bar')) {
win.on("resize load",function(){
var wpbar, w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth;
if (x <= 782) {
wpbar = 46;
} else if (x > 782) {
wpbar = 32;
}
});
}
return wpbar;
}
I want to use the variable wpbar into this another function:
$(document).ready(function($) {
"use strict";
var wpbar = wp_adminbar();
console.log(wpbar); // Returns: 0
});
I'm stuck in that. Edit: Actually, return wpbar; is not working at all.
Edit: Full code of a function contaning the first function. In this case, it works:
$(document).ready(function($) {
"use strict";
var win = $(window),
nav_fixed = $('.enable-fixed'),
header = $('#header-v1');
if (!nav_fixed.length || !header.length) return;
// WordPress Toolbar
var wpbar = 0;
if ($('body').hasClass('admin-bar')) {
win.on("resize load",function(){
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth;
if (x <= 782) {
wpbar = 46;
} else if (x > 782) {
wpbar = 32;
}
});
}
var max_h = 89,
min_h = 55,
var_h = max_h - min_h,
menu = $('.sticky-wrapper-v1, #header-v1, #header-v1 .wrap, #header-v1 .menuwrap ul:first-child > li > a, #header-v1 .main-nav-search a'),
logo = $('#header-v1 #logo, #header-v1 #logo img'),
nav = $('#navigation'),
set_height = function(){
var st = win.scrollTop() + wpbar,
new_h = 0,
new_p = 0,
wrapper = $('.sticky-wrapper-v1'),
top_p = wrapper.offset().top;
if (st <= top_p) {
new_h = max_h;
new_p = 0;
} else if (st <= (top_p + var_h)) {
new_h = max_h - st + top_p;
new_p = st - top_p;
header.removeClass("header-scrolled");
} else {
new_h = min_h;
new_p = var_h;
header.addClass("header-scrolled");
}
wrapper.css('margin-bottom', new_p);
menu.css({'height': new_h + 'px', 'lineHeight': new_h + 'px'});
logo.css({'maxHeight': new_h + 'px'});
nav.css({'height': new_h + 'px'});
};
win.one("resize",function(){
$(".navbtn").toggle(function() {
set_height;
}, function () {
set_height;
});
set_height;
});
win.on('debouncedresize', function(){
max_h = $(menu).attr('style',"").filter(':first').height();
set_height();
});
win.on('scroll', function(){
window.requestAnimationFrame( set_height );
});
set_height();
});
Online sample http://jsfiddle.net/dhCLd/
A simple drag magnify,
(function($) {
$.fn.drag = function(opt) {
opt = $.extend({
handle: "",
cursor:"move"}, opt);
if(opt.handle === "") {
var $el = this;
} else {
var $el = this.find(opt.handle);
}
return $el.css('cursor', opt.cursor).on("mousedown", function(e) {
if(opt.handle === "") {
var $drag = $(this).addClass('draggable');
} else {
var $drag = $(this).addClass('active-handle').parent().addClass('draggable');
}
var z_idx = $drag.css('z-index'),
native_width = 0,
native_height = 0;
$drag.css('z-index', 1000).parents('.magnify').on("mousemove", function(e) {
if(!native_width && !native_height){
var image_object = new Image();
image_object.src = $(".small").attr("src");
native_width = image_object.width;
native_height = image_object.height;
}else{
var magnify_offset = $drag.parents('.magnify').offset();
var mx = e.pageX - magnify_offset.left;
var my = e.pageY - magnify_offset.top;
var rx = Math.round(mx/$(".small").width()*native_width - $drag.width()/2)*-1;
var ry = Math.round(my/$(".small").height()*native_height - $drag.height()/2)*-1;
var px = mx - $(".large").width()/2;
var py = my - $(".large").height()/2;
var bgp = rx + "px " + ry + "px";
$('.draggable').css({left:px, top:py, backgroundPosition: bgp}).on("mouseup", function() {
$(this).removeClass('draggable').css('z-index', z_idx);
});
}
});
e.preventDefault();
}).on("mouseup", function() {
if(opt.handle === "") {
$(this).removeClass('draggable');
} else {
$(this).removeClass('active-handle').parent().removeClass('draggable');
}
});
}
})(jQuery);
How can I make the "magnify" stops at the edges around the .small` image, if outside of the image then undraggable. If someone could help?
You can just limit the values of mx (in range [0,magnify's width]) and my (in range [0, magnify's height]):
var magnify = $drag.closest('.magnify');
var magnify_offset = magnify.offset();
var mx = Math.min(Math.max(e.pageX - magnify_offset.left,0),magnify.width());
var my = Math.min(Math.max(e.pageY - magnify_offset.top,0), magnify.height());
Updated demo.
To make the magnifying glass undraggable when it's outside a bounded area, simply test the position of the background image as it is being drag:
var cH = 175/2; //Half of the magnifying glass
if(rx > cH|| ry > cH || rx < -579 + cH || ry < -1107 + cH){ //579 and 1107 are the dimension of the background image
$(this).trigger("mouseup"); //Make it undraggable
return false;
}
I'm developping this mobile app and I'm usint this (https://github.com/krisrak/appframework-templates/blob/master/template-CarouselViewApp.html) as a carousel to change through content on a page. http://jsfiddle.net/nafis56/qCkqb/
So for this I need to mess around in HTML, CSS and Jquery. Unfortonetly I'm still very green at javascript so I need your help. I changed an ID to a Class because I need to call it more than once in the same page. In the original template I refeered to, it comes as an ID. So I did this to change it:
Changed matching code on html to call it as a Class.
<div class="panel" title="Desiree Charms" id="desiree_charms" style="overflow: hidden;"
data-appbuilder-object="page">
<div class="carousel">
<div class="carousel_page">
<h2>Desiree Charms</h2>
<p><img src="images/desiree_charms.jpg" style="width: 85%; height: 85%; display: block; margin-left: auto; margin-right: auto "
data-appbuilder-object="image" class="" title="">
</p>
</div>
<div class="carousel_page">
<h2>Page Two</h2>
<p>Text and images for Page Two goes here. Swipe to go to the
next page.</p>
</div>
</div>
<div class="carousel_dots"></div>
</div>
also this on the html.
<script>
$.ui.autoLaunch = false;
$.ui.animateHeaders = false;
$(document).ready(function(){
$.ui.launch();
});
$.ui.ready(function(){
carouselSetup();
});
function carouselSetup(){
// set size of carousel
$(".carousel").width($(".carousel").closest(".panel").width());
$(".carousel").height($(".carousel").closest(".panel").height()-25);
var options={
vertical:false, // page up/down
horizontal:true, // page left/right
pagingDiv:"carousel_dots", // div to hold the dots for paging
pagingCssName:"carousel_paging", //classname for the paging dots
pagingCssNameSelected: "carousel_paging_selected", //classname for the selected page dots
wrap:true //Creates a continuous carousel
}
var carousel = $(".carousel").carousel(options);
}
Changed # to . on Css.
.carousel {
overflow:hidden;
margin:0 -10px;
}
.carousel_page {
overflow: auto;
-webkit-scrolling:touch;
padding:0 10px;
}
.carousel_dots {
text-align: center;
margin-left: auto;
margin-right: auto;
clear: both;
position:relative;
top:0;
z-index:200;
}
.carousel_paging {
border-radius: 10px;
background: #ccc;
width: 10px;
height: 10px;
display:inline-block;
}
.carousel_paging_selected {
border-radius: 10px;
background: #000;
width: 10px;
height: 10px;
display:inline-block;
}
.carousel h2 {
text-align: center;
}
This is the jquery ( I didn't change anything)
/**
* af.web.carousel - a carousel library for App Framework apps
* #copyright 2011 - Intel
*
*/
(function($) {
var cache = [];
var objId=function(obj){
if(!obj.afmCarouselId) obj.afmCarouselId=$.uuid();
return obj.afmCarouselId;
}
$.fn.carousel = function(opts) {
var tmp, id;
for (var i = 0; i < this.length; i++) {
//cache system
id = objId(this[i]);
if(!cache[id]){
tmp = new carousel(this[i], opts);
cache[id] = tmp;
} else {
tmp = cache[id];
}
}
return this.length == 1 ? tmp : this;
};
var carousel = (function() {
var translateOpen =$.feat.cssTransformStart;
var translateClose = $.feat.cssTransformEnd;
var carousel = function(containerEl, opts) {
if (typeof containerEl === "string" || containerEl instanceof String) {
this.container = document.getElementById(containerEl);
} else {
this.container = containerEl;
}
if (!this.container) {
alert("Error finding container for carousel " + containerEl);
return;
}
if (this instanceof carousel) {
for (var j in opts) {
if (opts.hasOwnProperty(j)) {
this[j] = opts[j];
}
}
} else {
return new carousel(containerEl, opts);
}
var that = this;
af(this.container).bind('destroy', function(e){
var id = that.container.afmCarouselId;
//window event need to be cleaned up manually, remaining binds are automatically killed in the dom cleanup process
window.removeEventListener("orientationchange", that.orientationHandler, false);
if(cache[id]) delete cache[id];
e.stopPropagation();
});
this.pagingDiv = this.pagingDiv ? document.getElementById(this.pagingDiv) : null;
// initial setup
this.container.style.overflow = "hidden";
if (this.vertical) {
this.horizontal = false;
}
var el = document.createElement("div");
this.container.appendChild(el);
var $el=$(el);
var $container=$(this.container);
var data = Array.prototype.slice.call(this.container.childNodes);
while(data.length>0)
{
var myEl=data.splice(0,1);
myEl=$container.find(myEl);
if(myEl.get(0)==el)
continue;
$el.append(myEl.get(0));
}
if (this.horizontal) {
el.style.display = "block";
el.style['float']="left";
}
else {
el.style.display = "block";
}
this.el = el;
this.refreshItems();
var afEl = af(el);
afEl.bind('touchmove', function(e) {that.touchMove(e);});
afEl.bind('touchend', function(e) {that.touchEnd(e);});
afEl.bind('touchstart', function(e) {that.touchStart(e);});
this.orientationHandler = function() {that.onMoveIndex(that.carouselIndex,0);};
window.addEventListener("orientationchange", this.orientationHandler, false);
};
carousel.prototype = {
wrap:true,
startX: 0,
startY: 0,
dx: 0,
dy: 0,
glue: false,
myDivWidth: 0,
myDivHeight: 0,
cssMoveStart: 0,
childrenCount: 0,
carouselIndex: 0,
vertical: false,
horizontal: true,
el: null,
movingElement: false,
container: null,
pagingDiv: null,
pagingCssName: "carousel_paging",
pagingCssNameSelected: "carousel_paging_selected",
pagingFunction: null,
lockMove:false,
okToMove: false,
// handle the moving function
touchStart: function(e) {
this.okToMove = false;
this.myDivWidth = numOnly(this.container.clientWidth);
this.myDivHeight = numOnly(this.container.clientHeight);
this.lockMove=false;
if (e.touches[0].target && e.touches[0].target.type !== undefined) {
var tagname = e.touches[0].target.tagName.toLowerCase();
if (tagname === "select" || tagname === "input" || tagname === "button") // stuff we need to allow
{
return;
}
}
if (e.touches.length === 1) {
this.movingElement = true;
this.startY = e.touches[0].pageY;
this.startX = e.touches[0].pageX;
var cssMatrix=$.getCssMatrix(this.el);
if (this.vertical) {
try {
this.cssMoveStart = numOnly(cssMatrix.f);
} catch (ex1) {
this.cssMoveStart = 0;
}
} else {
try {
this.cssMoveStart = numOnly(cssMatrix.e);
} catch (ex1) {
this.cssMoveStart = 0;
}
}
}
},
touchMove: function(e) {
if(!this.movingElement)
return;
if (e.touches.length > 1) {
return this.touchEnd(e);
}
var rawDelta = {
x: e.touches[0].pageX - this.startX,
y: e.touches[0].pageY - this.startY
};
if (this.vertical) {
var movePos = { x: 0, y: 0 };
this.dy = e.touches[0].pageY - this.startY;
this.dy += this.cssMoveStart;
movePos.y = this.dy;
e.preventDefault();
//e.stopPropagation();
} else {
if ((!this.lockMove&&isHorizontalSwipe(rawDelta.x, rawDelta.y))||Math.abs(this.dx)>5) {
var movePos = {x: 0,y: 0};
this.dx = e.touches[0].pageX - this.startX;
this.dx += this.cssMoveStart;
e.preventDefault();
// e.stopPropagation();
movePos.x = this.dx;
}
else
return this.lockMove=true;
}
var totalMoved = this.vertical ? ((this.dy % this.myDivHeight) / this.myDivHeight * 100) * -1 : ((this.dx % this.myDivWidth) / this.myDivWidth * 100) * -1; // get a percentage of movement.
if (!this.okToMove) {
oldStateOkToMove= this.okToMove;
this.okToMove = this.glue ? Math.abs(totalMoved) > this.glue && Math.abs(totalMoved) < (100 - this.glue) : true;
if (this.okToMove && !oldStateOkToMove) {
$.trigger(this,"movestart",[this.el]);
}
}
if (this.okToMove && movePos)
this.moveCSS3(this.el, movePos);
},
touchEnd: function(e) {
if (!this.movingElement) {
return;
}
$.trigger(this,"movestop",[this.el]);
// e.preventDefault();
// e.stopPropagation();
var runFinal = false;
// try {
var cssMatrix=$.getCssMatrix(this.el);
var endPos = this.vertical ? numOnly(cssMatrix.f) : numOnly(cssMatrix.e);
if (1==2&&endPos > 0) {
this.moveCSS3(this.el, {
x: 0,
y: 0
}, "300");
} else {
var totalMoved = this.vertical ? ((this.dy % this.myDivHeight) / this.myDivHeight * 100) * -1 : ((this.dx % this.myDivWidth) / this.myDivWidth * 100) * -1; // get a percentage of movement.
// Only need
// to drag 3% to trigger an event
var currInd = this.carouselIndex;
if (endPos < this.cssMoveStart && totalMoved > 3) {
currInd++; // move right/down
} else if ((endPos > this.cssMoveStart && totalMoved < 97)) {
currInd--; // move left/up
}
var toMove=currInd;
//Checks for infinite - moves to placeholders
if(this.wrap){
if (currInd > (this.childrenCount - 1)) {
currInd = 0;
toMove=this.childrenCount;
}
if (currInd < 0) {
currInd = this.childrenCount-1;
toMove=-1;
}
}
else {
if(currInd<0)
currInd=0;
if(currInd>this.childrenCount-1)
currInd=this.childrenCount-1;
toMove=currInd;
}
var movePos = {
x: 0,
y: 0
};
if (this.vertical) {
movePos.y = (toMove * this.myDivHeight * -1);
}
else {
movePos.x = (toMove * this.myDivWidth * -1);
}
this.moveCSS3(this.el, movePos, "150");
if (this.pagingDiv && this.carouselIndex !== currInd) {
document.getElementById(this.container.id + "_" + this.carouselIndex).className = this.pagingCssName;
document.getElementById(this.container.id + "_" + currInd).className = this.pagingCssNameSelected;
}
if (this.carouselIndex != currInd)
runFinal = true;
this.carouselIndex = currInd;
//This is for the infinite ends - will move to the correct position after animation
if(this.wrap){
if(toMove!=currInd){
var that=this;
window.setTimeout(function(){
that.onMoveIndex(currInd,"1ms");
},155);
}
}
}
//} catch (e) {
// console.log(e);
// }
this.dx = 0;
this.movingElement = false;
this.startX = 0;
this.dy = 0;
this.startY = 0;
if (runFinal && this.pagingFunction && typeof this.pagingFunction == "function")
this.pagingFunction(this.carouselIndex);
},
onMoveIndex: function(newInd,transitionTime) {
this.myDivWidth = numOnly(this.container.clientWidth);
this.myDivHeight = numOnly(this.container.clientHeight);
var runFinal = false;
if(document.getElementById(this.container.id + "_" + this.carouselIndex))
document.getElementById(this.container.id + "_" + this.carouselIndex).className = this.pagingCssName;
var newTime = Math.abs(newInd - this.carouselIndex);
var ind = newInd;
if (ind < 0)
ind = 0;
if (ind > this.childrenCount - 1) {
ind = this.childrenCount - 1;
}
var movePos = {
x: 0,
y: 0
};
if (this.vertical) {
movePos.y = (ind * this.myDivHeight * -1);
}
else {
movePos.x = (ind * this.myDivWidth * -1);
}
var time =transitionTime?transitionTime: 50 + parseInt((newTime * 20));
this.moveCSS3(this.el, movePos, time);
if (this.carouselIndex != ind)
runFinal = true;
this.carouselIndex = ind;
if (this.pagingDiv) {
var tmpEl = document.getElementById(this.container.id + "_" + this.carouselIndex);
if(tmpEl) tmpEl.className = this.pagingCssNameSelected;
}
if (runFinal && this.pagingFunction && typeof this.pagingFunction == "function")
this.pagingFunction(currInd);
},
moveCSS3: function(el, distanceToMove, time, timingFunction) {
if (!time)
time = 0;
else
time = parseInt(time);
if (!timingFunction)
timingFunction = "linear";
el.style[$.feat.cssPrefix+"Transform"] = "translate" + translateOpen + distanceToMove.x + "px," + distanceToMove.y + "px" + translateClose;
el.style[$.feat.cssPrefix+"TransitionDuration"] = time + "ms";
el.style[$.feat.cssPrefix+"BackfaceVisibility"] = "hidden";
el.style[$.feat.cssPrefix+"TransitionTimingFunction"] = timingFunction;
},
addItem: function(el) {
if (el && el.nodeType) {
this.container.childNodes[0].appendChild(el);
this.refreshItems();
}
},
refreshItems: function() {
var childrenCounter = 0;
var that = this;
var el = this.el;
$(el).children().find(".prevBuffer").remove();
$(el).children().find(".nextBuffer").remove();
n = el.childNodes[0];
var widthParam;
var heightParam = "100%";
var elems = [];
for (; n; n = n.nextSibling) {
if (n.nodeType === 1) {
elems.push(n);
childrenCounter++;
}
}
//Let's put the buffers at the start/end
if(this.wrap){
var prep=$(elems[elems.length-1]).clone().get(0);
$(el).prepend(prep);
var tmp=$(elems[0]).clone().get(0);
$(el).append(tmp);
elems.push(tmp);
elems.unshift(prep);
tmp.style.position="absolute";
prep.style.position="absolute";
}
var param = (100 / childrenCounter) + "%";
this.childrenCount = childrenCounter;
widthParam = parseFloat(100 / childrenCounter) + "%";
for (var i = 0; i < elems.length; i++) {
if (this.horizontal) {
elems[i].style.width = widthParam;
elems[i].style.height = "100%";
elems[i].style['float']="left";
}
else {
elems[i].style.height = widthParam;
elems[i].style.width = "100%";
elems[i].style.display = "block";
}
}
//Clone the first and put it at the end
this.moveCSS3(el, {
x: 0,
y: 0
});
if (this.horizontal) {
el.style.width = Math.ceil((this.childrenCount) * 100) + "%";
el.style.height = "100%";
el.style['min-height'] = "100%"
if(this.wrap){
prep.style.left="-"+widthParam;
tmp.style.left="100%";
}
}
else {
el.style.width = "100%";
el.style.height = Math.ceil((this.childrenCount) * 100) + "%";
el.style['min-height'] = Math.ceil((this.childrenCount) * 100) + "%";
if(this.wrap){
prep.style.top="-"+widthParam;
tmp.style.top="100%";
}
}
// Create the paging dots
if (this.pagingDiv) {
this.pagingDiv.innerHTML = ""
for (i = 0; i < this.childrenCount; i++) {
var pagingEl = document.createElement("div");
pagingEl.id = this.container.id + "_" + i;
pagingEl.pageId = i;
if (i !== this.carouselIndex) {
pagingEl.className = this.pagingCssName;
}
else {
pagingEl.className = this.pagingCssNameSelected;
}
pagingEl.onclick = function() {
that.onMoveIndex(this.pageId);
};
var spacerEl = document.createElement("div");
spacerEl.style.width = "20px";
if(this.horizontal){
spacerEl.style.display = "inline-block";
spacerEl.innerHTML = " ";
}
else{
spacerEl.innerHTML=" ";
spacerEl.style.display="block";
}
this.pagingDiv.appendChild(pagingEl);
if (i + 1 < (this.childrenCount))
this.pagingDiv.appendChild(spacerEl);
pagingEl = null;
spacerEl = null;
}
if(this.horizontal){
this.pagingDiv.style.width = (this.childrenCount) * 50 + "px";
this.pagingDiv.style.height = "25px";
}
else {
this.pagingDiv.style.height = (this.childrenCount) * 50 + "px";
this.pagingDiv.style.width = "25px";
}
}
this.onMoveIndex(this.carouselIndex);
}
};
return carousel;
})();
function isHorizontalSwipe(xAxis, yAxis) {
var X = xAxis;
var Y = yAxis;
var Z = Math.round(Math.sqrt(Math.pow(X,2)+Math.pow(Y,2))); //the distance - rounded - in pixels
var r = Math.atan2(Y,X); //angle in radians
var swipeAngle = Math.round(r*180/Math.PI); //angle in degrees
if ( swipeAngle < 0 ) { swipeAngle = 360 - Math.abs(swipeAngle); } // for negative degree values
if (((swipeAngle <= 215) && (swipeAngle >= 155)) || ((swipeAngle <= 45) && (swipeAngle >= 0)) || ((swipeAngle <= 360) && (swipeAngle >= 315))) // horizontal angles with threshold
{return true; }
else {return false}
}
})(af);
Now, on the CSS file when I change .carousel_dots to #carousel_dots as it was originally. The carousel starts working. The problem is I need it as a class not an ID.
I'm pretty sure the problem is in the jquery, somewhere in there I need to set carousel_dots as a class and not an ID, but where?
Any help will be much apreciated, thanks.
jQuery is designed to trigger on HTML selectors, either elements, ID's or Class's. It's very common for it to trigger on ID's because, as you identified, they occur once and that isolates the action to that particular item.
I know that you changed the ID's to Class's because you want to use the CSS class multiple times. You can do this by using Class's. But, to maintain the jQuery logic, you should not change the ID's to Class's for that purpose. Use the ID's to synch with jQuery. Use Class's to control your CSS.
It's difficult to advise you regarding the case you displayed because you didn't identify the initial status and exactly how you changed it. If you can do that, we can be specific about what changes you should make. Good luck.
i have this page http://kreditmoney.ch/de/kreditantrag/index.php
Slider at right side can not work at IE9 and older version. I fixed error at IE11.
I assume that, the error is in this code:
.........
else {
this.fireEvent('onChange', this.step);
this.bkg.style.clip = "rect(0px "+ (parseInt(this.drag.value.now[this.z]) +3) + "px 10px 0px)"
........
This is full code:
var SliderMoj = new Class({
options: {
onChange: Class.empty,
onComplete: Class.empty,
onTick: function(pos){
this.moveKnob.setStyle(this.p, pos);
},
start: 0,
end: 100,
offset: 0,
knobheight: 20,
knobwidth: 14,
mode: 'horizontal',
clip_w:0,
clip_l:0,
isinit:true,
snap: false,
range: false,
numsteps:null
},
initialize: function(el, knob,bkg, options, maxknob) {
this.setOptions(options);
this.element = $(el);
this.knob = $(knob);
this.previousChange = this.previousEnd = this.step = -1;
this.bkg = $(bkg);
if(this.options.steps==null){
this.options.steps = this.options.end - this.options.start;
}
if(maxknob!=null)
this.maxknob = $(maxknob);
//else
// this.element.addEvent('mousedown', this.clickedElement.bindWithEvent(this));
var mod, offset;
switch(this.options.mode){
case 'horizontal':
this.z = 'x';
this.p = 'left';
mod = {'x': 'left', 'y': false};
offset = 'offsetWidth';
break;
case 'vertical':
this.z = 'y';
this.p = 'top';
mod = {'x': false, 'y': 'top'};
offset = 'offsetHeight';
}
this.max = this.element[offset] - this.knob[offset] + (this.options.offset * 2);
this.half = this.knob[offset]/2;
this.full = this.element[offset] - this.knob[offset] + (this.options.offset * 2);
this.min = $chk(this.options.range[0]) ? this.options.range[0] : 0;
this.getPos = this.element['get' + this.p.capitalize()].bind(this.element);
this.knob.setStyle('position', 'relative').setStyle(this.p, - this.options.offset);
this.range = this.max - this.min;
this.steps = this.options.steps || this.full;
this.stepSize = Math.abs(this.range) / this.steps;
this.stepWidth = this.stepSize * this.full / Math.abs(this.range) ;
if(maxknob != null) {
this.maxPreviousChange = -1;
this.maxPreviousEnd = -1;
this.maxstep = this.options.end;
this.maxknob.setStyle('position', 'relative').setStyle(this.p, + this.max - this.options.offset).setStyle('bottom', this.options.knobheight);
}
var lim = {};
//status = this.z
lim[this.z] = [- this.options.offset, this.max - this.options.offset];
//lim[this.z] = [100, this.max - this.options.offset];
this.drag = new Drag(this.knob, {
limit: lim,
modifiers: mod,
snap: 0,
onStart: function(){
this.draggedKnob();
}.bind(this),
onDrag: function(){
this.draggedKnob();
}.bind(this),
onComplete: function(){
this.draggedKnob();
this.end();
}.bind(this)
});
if(maxknob != null) {
this.maxdrag = new Drag(this.maxknob, {
limit: lim,
modifiers: mod,
snap: 0,
onStart: function(){
this.draggedKnob(1);
}.bind(this),
onDrag: function(){
this.draggedKnob(1);
}.bind(this),
onComplete: function(){
this.draggedKnob(1);
this.end();
}.bind(this)
});
}
if (this.options.snap) {
//this.drag.options.grid = Math.ceil(this.stepWidth);
this.drag.options.grid = (this.full)/this.options.numsteps ;
this.drag.options.limit[this.z][1] = this.full;
//this.drag.options.grid = this.drag.options.grid - (this.knob[offset]/this.options.numsteps);
status = "GRID - " + this.drag.options.grid + " , full = " + this.full// DEBUG
}
if (this.options.initialize) this.options.initialize.call(this);
},
setMin: function(stepMin){
this.step = stepMin.limit(this.options.start, this.options.end);
this.checkStep();
this.end();
this.moveKnob = this.knob;
this.bkg.style.clip = "rect(0px "+ (parseInt(this.toPosition(this.step)) +3) + "px 10px 0px)";
status =this.bkg.style.clip + " vl= " + parseInt(this.toPosition(this.step)) ; //Debug
this.fireEvent('onTick', this.toPosition(this.step));
return this;
},
setMax: function(stepMax){
this.maxstep = stepMax.limit(this.options.start, this.options.end);
this.checkStep(1);
this.end();
this.moveKnob = this.maxknob;
var w= Math.abs(this.toPosition(this.step)- this.toPosition(this.maxstep)) + 3 ;
var r = parseInt(this.clip_l + w);
this.bkg.style.clip = "rect(0px "+ r + "px 10px "+ this.clip_l + "px)";
this.fireEvent('onTick', this.toPosition(this.maxstep));
// For Init Only
if(this.options.isinit){
var lim = {}; var mi,mx;
mi = - this.options.offset;
mx= parseInt(this.maxknob.getStyle('left')) - this.options.offset-4 ;
lim[this.z] = [mi, mx];
this.drag.options.limit = lim;
this.options.isinit = false;
}
return this;
},
clickedElement: function(event){
var position = event.page[this.z] - this.getPos() - this.half;
position = position.limit(-this.options.offset, this.max -this.options.offset);
this.step = this.toStep(position);
//this.moveKnob = this.knob;
this.bkg.style.clip = "rect(0px "+ (parseInt(this.toPosition(this.step)) +3) + "px 10px 0px)"
//status =this.bkg.style.clip; //Debug
this.checkStep();
this.end();
this.fireEvent('onTick', position);
},
draggedKnob: function(mx){
var lim = {}; var mi,mx;
if(mx==null) {
this.step = this.toStep(this.drag.value.now[this.z]);
this.checkStep();
}else {
this.maxstep = this.toStep(this.maxdrag.value.now[this.z]);
this.checkStep(1);
}
},
checkStep: function(mx){
var lim = {}; var mi,mx;
var limm = {};
if(mx==null) {if (this.previousChange != this.step){this.previousChange = this.step;}}
else {if (this.maxPreviousChange != this.maxstep){this.maxPreviousChange = this.maxstep;}}
if(this.maxknob!=null) {
mi = - this.options.offset;
mx= parseInt(this.maxknob.getStyle('left')) - this.options.offset-4 ;
//mx= parseInt(this.maxknob.getStyle('left')) - this.options.offset ;
lim[this.z] = [mi, mx];
this.drag.options.limit = lim;
mi = parseInt(this.knob.getStyle('left'))-this.options.offset+22;
//mi = parseInt(this.knob.getStyle('left'))-this.options.offset;
mx= this.max - this.options.offset;
limm[this.z] = [mi, mx];
this.maxdrag.options.limit = limm;
if(this.step < this.maxstep){
this.fireEvent('onChange', { minpos: this.step, maxpos: this.maxstep });
//this.clip_l = parseInt(this.knob.getStyle('left'));
}
else{
this.fireEvent('onChange', { minpos: this.maxstep, maxpos: this.step });
//this.clip_l = (parseInt(this.maxknob.getStyle('left')) + 10) ;
}
this.clip_l = parseInt(this.knob.getStyle('left')) + 10;
//var w = Math.abs(parseInt(this.knob.getStyle('left')) - parseInt(this.maxknob.getStyle('left'))) + 3;
var w = Math.abs(parseInt(this.knob.getStyle('left')) - parseInt(this.maxknob.getStyle('left')));
//if(w > 3) w = w+3;
var r = parseInt(this.clip_l + w);
this.bkg.style.clip = "rect(0px "+ r + "px 10px "+ this.clip_l + "px)"
//status =this.bkg.style.clip + " w= " + w //Debug
}else {
this.fireEvent('onChange', this.step);
this.bkg.style.clip = "rect(0px "+ (parseInt(this.drag.value.now[this.z]) +3) + "px 10px 0px)"
}
},
end: function(){
if (this.previousEnd !== this.step || (this.maxknob != null && this.maxPreviousEnd != this.maxstep)) {
this.previousEnd = this.step;
if(this.maxknob != null) {
this.maxPreviousEnd = this.maxstep;
if(this.step < this.maxstep)
this.fireEvent('onComplete', { minpos: this.step + '', maxpos: this.maxstep + '' });
else
this.fireEvent('onComplete', { minpos: this.maxstep + '', maxpos: this.step + '' });
}else{
this.fireEvent('onComplete', this.step + '');
}
}
},
toStep: function(position){
return Math.round((position + this.options.offset) / this.max * this.options.steps) + this.options.start;
},
toPosition: function(step){
return (this.max * step / this.options.steps) - (this.max * this.options.start / this.options.steps) - this.options.offset;
}
});
SliderMoj.implement(new Events);
SliderMoj.implement(new Options);
Best regards,
Nemanja
I found solution for this problem.
The code should look like this:
'var SliderMoj = new
Class({
options: {
onChange: Class.empty,
onComplete: Class.empty,
onTick: function(pos){
this.moveKnob.setStyle(this.p, pos);
},
start: 0,
end: 100,
offset: 0,
knobheight: 20,
knobwidth: 14,
mode: 'horizontal',
clip_w:0,
clip_l:0,
isinit:true,
snap: false,
range: false,
numsteps:null
},
initialize: function(el, knob,bkg, options, maxknob) {
this.setOptions(options);
this.element = $(el);
this.knob = $(knob);
this.previousChange = this.previousEnd = this.step = -1;
this.bkg = $(bkg);
if(this.options.steps==null){
this.options.steps = this.options.end - this.options.start;
}
if(maxknob!=null)
this.maxknob = $(maxknob);
//else
// this.element.addEvent('mousedown', this.clickedElement.bindWithEvent(this));
var mod, offset;
switch(this.options.mode){
case 'horizontal':
this.z = 'x';
this.p = 'left';
mod = {'x': 'left', 'y': false};
offset = 'offsetWidth';
break;
case 'vertical':
this.z = 'y';
this.p = 'top';
mod = {'x': false, 'y': 'top'};
offset = 'offsetHeight';
}
this.max = this.element[offset] - this.knob[offset] + (this.options.offset * 2);
this.half = this.knob[offset]/2;
this.full = this.element[offset] - this.knob[offset] + (this.options.offset * 2);
this.min = $chk(this.options.range[0]) ? this.options.range[0] : 0;
this.getPos = this.element['get' + this.p.capitalize()].bind(this.element);
this.knob.setStyle('position', 'relative').setStyle(this.p, - this.options.offset);
this.range = this.max - this.min;
this.steps = this.options.steps || this.full;
this.stepSize = Math.abs(this.range) / this.steps;
this.stepWidth = this.stepSize * this.full / Math.abs(this.range) ;
if(maxknob != null) {
this.maxPreviousChange = -1;
this.maxPreviousEnd = -1;
this.maxstep = this.options.end;
this.maxknob.setStyle('position', 'relative').setStyle(this.p, + this.max - this.options.offset).setStyle('bottom', this.options.knobheight);
}
var lim = {};
//status = this.z
lim[this.z] = [- this.options.offset, this.max - this.options.offset];
//lim[this.z] = [100, this.max - this.options.offset];
this.drag = new Drag(this.knob, {
limit: lim,
modifiers: mod,
snap: 0,
onStart: function(){
this.draggedKnob();
}.bind(this),
onDrag: function(){
this.draggedKnob();
}.bind(this),
onComplete: function(){
this.draggedKnob();
this.end();
}.bind(this)
});
if(maxknob != null) {
this.maxdrag = new Drag(this.maxknob, {
limit: lim,
modifiers: mod,
snap: 0,
onStart: function(){
this.draggedKnob(1);
}.bind(this),
onDrag: function(){
this.draggedKnob(1);
}.bind(this),
onComplete: function(){
this.draggedKnob(1);
this.end();
}.bind(this)
});
}
if (this.options.snap) {
//this.drag.options.grid = Math.ceil(this.stepWidth);
this.drag.options.grid = (this.full)/this.options.numsteps ;
this.drag.options.limit[this.z][1] = this.full;
//this.drag.options.grid = this.drag.options.grid - (this.knob[offset]/this.options.numsteps);
status = "GRID - " + this.drag.options.grid + " , full = " + this.full// DEBUG
}
if (this.options.initialize) this.options.initialize.call(this);
},
setMin: function(stepMin){
this.step = stepMin.limit(this.options.start, this.options.end);
this.checkStep();
this.end();
this.moveKnob = this.knob;
this.bkg.style.clip = "rect(0px "+ (parseInt(this.toPosition(this.step)) +3) + "px 10px 0px)";
status =this.bkg.style.clip + " vl= " + parseInt(this.toPosition(this.step)) ; //Debug
this.fireEvent('onTick', this.toPosition(this.step));
return this;
},
setMax: function(stepMax){
this.maxstep = stepMax.limit(this.options.start, this.options.end);
this.checkStep(1);
this.end();
this.moveKnob = this.maxknob;
var w= Math.abs(this.toPosition(this.step)- this.toPosition(this.maxstep)) + 3 ;
var r = parseInt(this.clip_l + w);
this.bkg.style.clip = "rect(0px "+ r + "px 10px "+ this.clip_l + "px)";
this.fireEvent('onTick', this.toPosition(this.maxstep));
// For Init Only
if(this.options.isinit){
var lim = {}; var mi,mx;
mi = - this.options.offset;
mx= parseInt(this.maxknob.getStyle('left')) - this.options.offset-4 ;
lim[this.z] = [mi, mx];
this.drag.options.limit = lim;
this.options.isinit = false;
}
return this;
},
clickedElement: function(event){
var position = event.page[this.z] - this.getPos() - this.half;
position = position.limit(-this.options.offset, this.max -this.options.offset);
this.step = this.toStep(position);
//this.moveKnob = this.knob;
this.bkg.style.clip = "rect(0px "+ (parseInt(this.toPosition(this.step)) +3) + "px 10px 0px)"
//status =this.bkg.style.clip; //Debug
this.checkStep();
this.end();
this.fireEvent('onTick', position);
},
draggedKnob: function(mx){
var lim = {}; var mi,mx;
if(mx==null) {
this.step = this.toStep(this.drag.value.now[this.z]);
this.checkStep();
}else {
this.maxstep = this.toStep(this.maxdrag.value.now[this.z]);
this.checkStep(1);
}
},
checkStep: function(mx){
var lim = {}; var mi,mx;
var limm = {};
if(mx==null) {if (this.previousChange != this.step){this.previousChange = this.step;}}
else {if (this.maxPreviousChange != this.maxstep){this.maxPreviousChange = this.maxstep;}}
if(this.maxknob!=null) {
mi = - this.options.offset;
mx= parseInt(this.maxknob.getStyle('left')) - this.options.offset-4 ;
//mx= parseInt(this.maxknob.getStyle('left')) - this.options.offset ;
lim[this.z] = [mi, mx];
this.drag.options.limit = lim;
mi = parseInt(this.knob.getStyle('left'))-this.options.offset+22;
//mi = parseInt(this.knob.getStyle('left'))-this.options.offset;
mx= this.max - this.options.offset;
limm[this.z] = [mi, mx];
this.maxdrag.options.limit = limm;
if(this.step < this.maxstep){
this.fireEvent('onChange', { minpos: this.step, maxpos: this.maxstep });
//this.clip_l = parseInt(this.knob.getStyle('left'));
}
else{
this.fireEvent('onChange', { minpos: this.maxstep, maxpos: this.step });
//this.clip_l = (parseInt(this.maxknob.getStyle('left')) + 10) ;
}
this.clip_l = parseInt(this.knob.getStyle('left')) + 10;
//var w = Math.abs(parseInt(this.knob.getStyle('left')) - parseInt(this.maxknob.getStyle('left'))) + 3;
var w = Math.abs(parseInt(this.knob.getStyle('left')) - parseInt(this.maxknob.getStyle('left')));
//if(w > 3) w = w+3;
var r = parseInt(this.clip_l + w);
this.bkg.style.clip = "rect(0px "+ r + "px 10px "+ this.clip_l + "px)"
//status =this.bkg.style.clip + " w= " + w //Debug
}else {
this.fireEvent('onChange', this.step);
this.bkg.style.clip = "rect(0px "+ (parseInt(this.drag.value.now[this.z]) +3) + "px 10px 0px)"
}
},
end: function(){
if (this.previousEnd !== this.step || (this.maxknob != null && this.maxPreviousEnd != this.maxstep)) {
this.previousEnd = this.step;
if(this.maxknob != null) {
this.maxPreviousEnd = this.maxstep;
if(this.step < this.maxstep)
this.fireEvent('onComplete', { minpos: this.step + '', maxpos: this.maxstep + '' });
else
this.fireEvent('onComplete', { minpos: this.maxstep + '', maxpos: this.step + '' });
}else{
this.fireEvent('onComplete', this.step + '');
}
}
},
toStep: function(position){
return Math.round((position + this.options.offset) / this.max * this.options.steps) + this.options.start;
},
toPosition: function(step){
return (this.max * step / this.options.steps) - (this.max * this.options.start / this.options.steps) - this.options.offset;
}
});'
#kiran-rs