e.stopPropagation on children during webkit-transform rotate? - javascript

I have a circle that has a menu with objects positioned in a circle inside the circle. When the user drags their finger in any direction the circle spins along with the finger, however, when the user is spinning the wheel and happens to touch one of the objects inside (serves as a link) the circle "brakes" and stops spinning. I need to cancel the event bubble. I know I need to use event.stopPropagation and deal with the capture inside the event handler but I am having issues implementing this with a jQuery plugin (Touchy) that I found.
*MAKE SURE YOU ARE VIEWING IN CHROME WITH THE OVERRIDES SET TO EMULATE TOUCH EVENTS AND THAT THE DEVELOPER CONSOLE IS OPEN Command+Option+i on Mac!!! *
http://jsfiddle.net/ymtV3/
*MAKE SURE YOU ARE VIEWING IN CHROME WITH THE OVERRIDES SET TO EMULATE TOUCH EVENTS AND THAT THE DEVELOPER CONSOLE IS OPEN Command+Option+i on Mac!!! *
<div id="wheelMenu">
<div id="wheel">
<ul class="items">
<li class="flashOff"><span>Flash</span></li>
<li class="sceneOff"><span>Scene</span></li>
<li class="hdrOff"><span>Hdr</span></li>
<li class="panoramaOff"><span>Pana</span></li>
<li class="resolutionOff"><span>Resolu</span></li>
<li class="reviewOff"><span>Review</span></li>
<li class="continuousShootingOff"><span>Contin</span></li>
<li class="dropBoxOff"><span>DropBox</span></li>
<li class="timerOff"><span>Timer</span></li>
</ul>
</div>
</div>
(function ($) {
$.touchyOptions = {
useDelegation: false,
rotate: {
preventDefault: {
start: true,
move: true,
end: true
},
stopPropagation: {
start: true,
move: true,
end: true
},
requiredTouches: 1,
data: {},
proxyEvents: ["TouchStart", "TouchMove", "GestureChange", "TouchEnd"]
}
};
var proxyHandlers = {
handleTouchStart: function (e) {
var eventType = this.context,
$target = getTarget(e, eventType);
if ($target) {
var event = e.originalEvent,
touches = event.targetTouches,
camelDataName = 'touchy' + eventType.charAt(0).toUpperCase() + eventType.slice(1),
data = $target.data(camelDataName),
settings = data.settings;
if (settings.preventDefault.start) {
event.preventDefault();
}
if (settings.stopPropagation.start) {
event.stopPropagation();
}
if (touches.length === settings.requiredTouches) {
switch (eventType) {
case 'rotate':
if (touches.length === 1) {
ensureSingularStartData(data, touches, e.timeStamp);
console.log(eventType);
console.log(touches);
console.log(data);
} else {
var points = getTwoTouchPointData(e);
data.startPoint = {
"x": points.centerX,
"y": points.centerY
};
data.startDate = e.timeStamp;
}
var startPoint = data.startPoint;
$target.trigger('touchy-rotate', ['start', $target, {
"startPoint": startPoint,
"movePoint": startPoint,
"lastMovePoint": startPoint,
"velocity": 0,
"degrees": 0
}]);
break;
}
}
}
},
handleTouchMove: function (e) {
var eventType = this.context,
$target = getTarget(e, eventType);
if ($target) {
var event = e.originalEvent,
touches = event.targetTouches,
camelDataName = 'touchy' + eventType.charAt(0).toUpperCase() + eventType.slice(1),
data = $target.data(camelDataName),
settings = data.settings;
if (settings.preventDefault.move) {
event.preventDefault();
}
if (settings.stopPropagation.move) {
event.stopPropagation();
}
if (touches.length === settings.requiredTouches) {
switch (eventType) {
case 'rotate':
var lastMovePoint,
lastMoveDate,
movePoint,
moveDate,
lastMoveDate,
distance,
ms,
velocity,
targetPageCoords,
centerCoords,
radians,
degrees,
lastDegrees,
degreeDelta;
lastMovePoint = data.lastMovePoint = data.movePoint || data.startPoint;
lastMoveDate = data.lastMoveDate = data.moveDate || data.startDate;
movePoint = data.movePoint = {
"x": touches[0].pageX,
"y": touches[0].pageY
};
moveDate = data.moveDate = e.timeStamp;
if (touches.length === 1) {
targetPageCoords = data.targetPageCoords = data.targetPageCoords || getViewOffset(e.target);
centerCoords = data.centerCoords = data.centerCoords || {
"x": targetPageCoords.x + ($target.width() * 0.5),
"y": targetPageCoords.y + ($target.height() * 0.5)
};
} else {
var points = getTwoTouchPointData(e);
centerCoords = data.centerCoords = {
"x": points.centerX,
"y": points.centerY
};
if (hasGestureChange()) {
break;
}
}
radians = Math.atan2(movePoint.y - centerCoords.y, movePoint.x - centerCoords.x);
lastDegrees = data.lastDegrees = data.degrees;
degrees = data.degrees = radians * (180 / Math.PI);
degreeDelta = lastDegrees ? degrees - lastDegrees : 0;
ms = moveDate - lastMoveDate;
velocity = data.velocity = ms === 0 ? 0 : degreeDelta / ms;
$target.trigger('touchy-rotate', ['move', $target, {
"startPoint": data.startPoint,
"startDate": data.startDate,
"movePoint": movePoint,
"lastMovePoint": lastMovePoint,
"centerCoords": centerCoords,
"degrees": degrees,
"degreeDelta": degreeDelta,
"velocity": velocity
}]);
break;
}
}
}
},
handleGestureChange: function (e) {
var eventType = this.context,
$target = getTarget(e, eventType);
if ($target) {
var $target = $(e.target),
event = e.originalEvent,
touches = event.touches,
camelDataName = 'touchy' + eventType.charAt(0).toUpperCase() + eventType.slice(1),
data = $target.data(camelDataName);
if (data.preventDefault.move) {
event.preventDefault();
}
if (settings.stopPropagation.move) {
event.stopPropagation();
}
switch (eventType) {
case 'rotate':
var lastDegrees = data.lastDegrees = data.degrees,
degrees = data.degrees = event.rotation,
degreeDelta = lastDegrees ? degrees - lastDegrees : 0,
ms = data.moveDate - data.lastMoveDate,
velocity = data.velocity = ms === 0 ? 0 : degreeDelta / ms;
$target.trigger('touchy-rotate', ['move', $target, {
"startPoint": data.startPoint,
"startDate": data.startDate,
"movePoint": data.movePoint,
"lastMovePoint": data.lastMovePoint,
"centerCoords": data.centerCoords,
"degrees": degrees,
"degreeDelta": degreeDelta,
"velocity": velocity
}]);
break;
}
}
},
handleTouchEnd: function (e) {
var eventType = this.context,
$target = getTarget(e, eventType);
if ($target) {
var event = e.originalEvent,
camelDataName = 'touchy' + eventType.charAt(0).toUpperCase() + eventType.slice(1),
data = $target.data(camelDataName),
settings = data.settings;
if (settings.preventDefault.end) {
event.preventDefault();
}
if (settings.stopPropagation.end) {
event.stopPropagation();
}
switch (eventType) {
case 'rotate':
var degreeDelta = data.lastDegrees ? data.degrees - data.lastDegrees : 0;
$target.trigger('touchy-rotate', ['end', $target, {
"startPoint": data.startPoint,
"startDate": data.startDate,
"movePoint": data.movePoint,
"lastMovePoint": data.lastMovePoint,
"degrees": data.degrees,
"degreeDelta": degreeDelta,
"velocity": data.velocity
}]);
$.extend(data, {
"startPoint": null,
"startDate": null,
"movePoint": null,
"moveDate": null,
"lastMovePoint": null,
"lastMoveDate": null,
"targetPageCoords": null,
"centerCoords": null,
"degrees": null,
"lastDegrees": null,
"velocity": null
});
break;
}
}
}
},
ensureSingularStartData = function (data, touches, timeStamp) {
if (!data.startPoint) {
data.startPoint = {
"x": touches[0].pageX,
"y": touches[0].pageY
}
}
if (!data.startDate) {
data.startDate = timeStamp;
}
},
hasGestureChange = function () {
return (typeof window.ongesturechange == "object");
},
getTarget = function (e, eventType) {
var $delegate,
$target = false,
i = 0,
len = boundElems[eventType].length
if ($.touchyOptions.useDelegation) {
for (; i < len; i += 1) {
$delegate = $(boundElems[eventType][i]).has(e.target);
if ($delegate.length > 0) {
$target = $delegate;
break;
}
}
} else if (boundElems[eventType] && boundElems[eventType].index(e.target) != -1) {
$target = $(e.target)
}
return $target;
},
getViewOffset = function (node, singleFrame) {
function addOffset(node, coords, view) {
var p = node.offsetParent;
coords.x += node.offsetLeft - (p ? p.scrollLeft : 0);
coords.y += node.offsetTop - (p ? p.scrollTop : 0);
if (p) {
if (p.nodeType == 1) {
var parentStyle = view.getComputedStyle(p, '');
if (parentStyle.position != 'static') {
coords.x += parseInt(parentStyle.borderLeftWidth);
coords.y += parseInt(parentStyle.borderTopWidth);
if (p.localName == 'TABLE') {
coords.x += parseInt(parentStyle.paddingLeft);
coords.y += parseInt(parentStyle.paddingTop);
} else if (p.localName == 'BODY') {
var style = view.getComputedStyle(node, '');
coords.x += parseInt(style.marginLeft);
coords.y += parseInt(style.marginTop);
}
} else if (p.localName == 'BODY') {
coords.x += parseInt(parentStyle.borderLeftWidth);
coords.y += parseInt(parentStyle.borderTopWidth);
}
var parent = node.parentNode;
while (p != parent) {
coords.x -= parent.scrollLeft;
coords.y -= parent.scrollTop;
parent = parent.parentNode;
}
addOffset(p, coords, view);
}
} else {
if (node.localName == 'BODY') {
var style = view.getComputedStyle(node, '');
coords.x += parseInt(style.borderLeftWidth);
coords.y += parseInt(style.borderTopWidth);
var htmlStyle = view.getComputedStyle(node.parentNode, '');
coords.x -= parseInt(htmlStyle.paddingLeft);
coords.y -= parseInt(htmlStyle.paddingTop);
}
if (node.scrollLeft) coords.x += node.scrollLeft;
if (node.scrollTop) coords.y += node.scrollTop;
var win = node.ownerDocument.defaultView;
if (win && (!singleFrame && win.frameElement)) addOffset(win.frameElement, coords, win);
}
}
......seee the rest on the JS Fiddle

Related

Vue drag event handlers not firing

I'm trying to follow along with this article to make an item move anywhere on the screen by dragging it: https://www.kirupa.com/html5/drag.htm The thing is that the article is in regular JavaScript and I'm using Vue so the way event handlers get handled are slightly different. For some reason, #dragStart and #drag don't fire at all but #dragEnd does fire when the user stops dragging the item.
Only div that I'm using for this
<div class="pip" draggable="true" #dragStart="dragStart" #drag="drag" #dragend="dragEnd">
Script tag
data() {
return {
active: false,
currentX: null,
currentY: null,
initialX: null,
initialY: null,
xOffset: 0,
yOffset: 0,
};
},
methods: {
dragStart(event) {
console.log('start');
const dragItem = document.querySelector('.pip');
if (event.type === 'touchstart') {
this.initialX = event.touches[0].clientX - this.xOffset;
this.initialY = event.touches[0].clientY - this.yOffset;
} else {
this.initialX = event.clientX - this.xOffset;
this.initialY = event.clientY - this.yOffset;
}
if (event.target === dragItem) {
this.active = true;
}
},
drag(event) {
console.log('drag');
const dragItem = document.querySelector('.pip');
if (this.active) {
event.preventDefault();
if (event.type === 'touchmove') {
this.currentX = event.touches[0].clientX - this.initialX;
this.currentY = event.touches[0].clientY - this.initialY;
} else {
this.currentX = event.clientX - this.initialX;
this.currentY = event.clientY - this.initialY;
}
this.xOffset = this.currentX;
this.yOffset = this.currentY;
this.setTranslate(this.currentX, this.currentY, dragItem);
}
},
dragEnd() {
console.log('end');
this.initialX = this.currentX;
this.initialY = this.currentY;
this.active = false;
// event.target.style.bottom = '0px';
// event.target.style.top = `${event.clientY - event.target.offsetHeight / 2}px`;
// event.target.style.left = `${event.clientX - event.target.offsetWidth / 2}px`;
// console.log(event);
},
setTranslate(xPos, yPos, el) {
el.style.transform = "translate3d(' + xPos + 'px, ' + yPos + 'px, 0)";
},

Lagging FPS in animation with requestAnim or TimeOut

I'm trying to get a good animation with constant fps, but nothing works. I'm using threejs, webgl to render the scene and for the animation loop I found two ways (is there a third?), which is either requestAnimationFrame(...) or by setTimeOut(). Both don't guarantee that the fps is constant, but I'm fixing it by updating the object position by the timedelta of window.performance.now(). But I still have lagspikes which one can clearly see. So how can I fix this? It's obviously possibly because there are games like doom which don't lag.
My example with full src-code can be found here:
http://sc2tube.com:8080/test/three.html
the relevant code:
function animate() {
requestAnimationFrame( animate );
// calculate how long the last frame was
var timefix = (window.performance.now() - last)/(1000/30);
last = window.performance.now();
var oldX = object.position.x;
// calculate updateX including the timefix
var updateX = oldX + (10 / 30 * 100) * dx * timefix;
// update the position of the object
object.position.x = updateX;
// render the scene
renderer.render(scene, camera);
}
worker.js:
self.addEventListener('message', function(e) {
setInterval(function(){
now = self.performance.now()
timefix = (now - last)/(1000/100);
last = now;
x += 5*timefix*dx;
self.postMessage(x);
}, 1000/100);
}, false);
var test;
var dx = 1, dy = 0;
var speed = 0.5;
var activeKey = 0;
// Set up the scene, camera, and renderer as global variables.
var scene, camera, renderer;
init();
animate();
// Sets up the scene.
function init() {
// Create the scene and set the scene size.
scene = new THREE.Scene();
var WIDTH = window.innerWidth - 50,
HEIGHT = 500;
// Create a renderer and add it to the DOM.
renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setSize(WIDTH, HEIGHT);
document.body.appendChild(renderer.domElement);
camera = new THREE.OrthographicCamera( 0, WIDTH, 200, -HEIGHT, 1, 1000 );
camera.position.set(0,0,100);
scene.add(camera);
console.log(WIDTH);
window.addEventListener('resize', function() {
var WIDTH = window.innerWidth - 50,
HEIGHT = window.innerHeight - 50;
renderer.setSize(WIDTH, HEIGHT);
camera.aspect = WIDTH / HEIGHT;
camera.updateProjectionMatrix();
});
renderer.setClearColor();
var loader = new THREE.ObjectLoader();
loader.parse({
"metadata" : {
"type" : "Object",
"version" : 4.3,
"generator" : "Blender Script"
},
"object" : {
"name" : "red_cube.Material",
"type" : "Mesh",
"uuid" : "6071e8f2-79ae-5660-8d2b-aa675c566703",
"matrix" : [1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],
"geometry" : "5d6cbd93-cf58-58a9-b0a7-5be9e5794547",
"material" : "5e847bd4-84a9-5d4b-a8fb-c567e27f7561"
},
"geometries" : [{
"name" : "red_cube.Material",
"type" : "BufferGeometry",
"uuid" : "5d6cbd93-cf58-58a9-b0a7-5be9e5794547",
"data" : {
"attributes" : {
"position" : {
"type" : "Float32Array",
"itemSize" : 3,
"array" : [0.79906648,-0.73424673,-0.87263167,0.79906648,-0.73424661,1.1273682,-1.2009337,-0.73424661,1.1273681,-1.2009332,-0.73424673,-0.87263215,0.79906696,1.2657533,-0.87263131,-1.2009335,1.2657533,-0.87263179,-1.2009339,1.2657533,1.1273677,0.79906583,1.2657533,1.1273688,0.79906648,-0.73424673,-0.87263167,0.79906696,1.2657533,-0.87263131,0.79906583,1.2657533,1.1273688,0.79906648,-0.73424661,1.1273682,0.79906648,-0.73424661,1.1273682,0.79906583,1.2657533,1.1273688,-1.2009339,1.2657533,1.1273677,-1.2009337,-0.73424661,1.1273681,-1.2009337,-0.73424661,1.1273681,-1.2009339,1.2657533,1.1273677,-1.2009335,1.2657533,-0.87263179,-1.2009332,-0.73424673,-0.87263215,0.79906696,1.2657533,-0.87263131,0.79906648,-0.73424673,-0.87263167,-1.2009332,-0.73424673,-0.87263215,-1.2009335,1.2657533,-0.87263179]
},
"normal" : {
"type" : "Float32Array",
"itemSize" : 3,
"array" : [-1.0658141e-14,-1,5.9604645e-08,-1.0658141e-14,-1,5.9604645e-08,-1.0658141e-14,-1,5.9604645e-08,-1.0658141e-14,-1,5.9604645e-08,0,1,0,0,1,0,0,1,0,0,1,0,1,4.4703416e-08,2.8312209e-07,1,4.4703416e-08,2.8312209e-07,1,4.4703416e-08,2.8312209e-07,1,4.4703416e-08,2.8312209e-07,-2.9802322e-07,-5.9604723e-08,1,-2.9802322e-07,-5.9604723e-08,1,-2.9802322e-07,-5.9604723e-08,1,-2.9802322e-07,-5.9604723e-08,1,-1,-1.1920929e-07,-2.3841858e-07,-1,-1.1920929e-07,-2.3841858e-07,-1,-1.1920929e-07,-2.3841858e-07,-1,-1.1920929e-07,-2.3841858e-07,2.3841858e-07,1.7881393e-07,-1,2.3841858e-07,1.7881393e-07,-1,2.3841858e-07,1.7881393e-07,-1,2.3841858e-07,1.7881393e-07,-1]
},
"index" : {
"type" : "Uint32Array",
"itemSize" : 1,
"array" : [0,1,2,2,3,0,4,5,6,6,7,4,8,9,10,10,11,8,12,13,14,14,15,12,16,17,18,18,19,16,20,21,22,22,23,20]
}
}
}
}],
"materials" : [{
"name" : "Material",
"type" : "MeshBasicMaterial",
"uuid" : "5e847bd4-84a9-5d4b-a8fb-c567e27f7561",
"transparent" : false,
"opacity" : 1,
"color" : 10682379
}]
}, function(object){
test = object;
object.scale.set(50,50,50);
scene.add(object)
});
document.addEventListener('keydown', function(e) {
if (activeKey == e.keyCode) return;
activeKey = e.keyCode;
//left
if (e.keyCode == 37) {
dx = -1;
}
//top
else if (e.keyCode == 38) {
dy = 1;
}
//right
else if (e.keyCode == 39) {
dx = 1;
}
//bottom
else if (e.keyCode == 40) {
dy = -1;
}
});
document.addEventListener('keyup', function(e) {
switch (e.keyCode) {
case 37: // left
case 39: // right
dx = 0;
break;
case 38: // up
case 40: // down
dy = 0;
break;
}
activeKey = 0;
});
}
var start;
var last;
function animate() {
requestAnimationFrame( animate );
if(start == null) {
start = window.performance.now();
last = start;
}
var timefix = (window.performance.now() - last)/(1000/30);
last = window.performance.now();
if(test != null) {
var oldX = test.position.x;
var oldY = test.position.y;
var updateX = oldX + (10 / 30 * 100) * dx * speed * timefix;
var updateY = oldY + (10 / 30 * 100) * dy * speed * timefix;
if(updateX > 1800 ) {
dx = -1;
} else if(updateX < 100) {
dx = 1;
}
test.position.x = updateX;
test.position.y = oldY + (10 / 30 * 100) * dy * speed * timefix;
var text = document.getElementById('panel');
text.innerHTML = timefix;
renderer.render(scene, camera);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/84/three.js"></script>
<body style="margin: 0;">
<div id="panel">TEST
</div>
<br>
</body>
The problem is something called game ticks.
What you need is threads.
one rendering thread.
one game thread.
For the game thread I advice a webworker:
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers
You let the game thread run every 50ms to update game logic. it should 'sleep" inbetween.
You post stuff back to rendering thread, which updates everything and interprolates the trajectories for currentpos to next pos in 50 ms.
tick 1. 0MS
game thread:
spawn block at 0.0
push gamestate to rendering thread
rendering thread
gather entities.
update entities for location if moving
draw entities at pos
tick 2. 50ms
game thread:
get entities
trigger update functions
red block moves left 20
push gamestate to rendering thread
rendering thread
gather entities.
update entities for location if moving
red block moves from 0 to 20
avg frames per tick 4
interprolated movement per tick, 5 px.
update red to 5
draw entities at pos
edit
Added example code of how to utilise render threads.
Basically you have the same objects in the game thread(webworker) as in the render thread.
Only difference is, render thread has has render instructions(onRender) and game loop has Update instructions(on update)
So they are the same, but also different.
Take a look.
function getInlineJS() {
var js = document.querySelector('[type="javascript/worker"]').textContent;
var blob = new Blob([js], {"type": "text\/plain"});
return URL.createObjectURL(blob);
}
var RedCube = function(id) {
this.cube = null;
this.type = 'redcube';
if(typeof id === undefined) {
this.entityId = generateId();
}
else {
this.entityId = id;
}
this.lastX = 0;
this.x = 0;
}
RedCube.prototype.getType = function() {
return this.type;
}
RedCube.prototype.onUpdate = function() {
this.x += 20;
}
RedCube.prototype.loadCube = function(scene, renderer) {
var that = this;
var loader = new THREE.ObjectLoader();
loader.parse({
"metadata" : {
"type" : "Object",
"version" : 4.3,
"generator" : "Blender Script"
},
"object" : {
"name" : "red_cube.Material",
"type" : "Mesh",
"uuid" : "6071e8f2-79ae-5660-8d2b-aa675c566703",
"matrix" : [1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],
"geometry" : "5d6cbd93-cf58-58a9-b0a7-5be9e5794547",
"material" : "5e847bd4-84a9-5d4b-a8fb-c567e27f7561"
},
"geometries" : [{
"name" : "red_cube.Material",
"type" : "BufferGeometry",
"uuid" : "5d6cbd93-cf58-58a9-b0a7-5be9e5794547",
"data" : {
"attributes" : {
"position" : {
"type" : "Float32Array",
"itemSize" : 3,
"array" : [0.79906648,-0.73424673,-0.87263167,0.79906648,-0.73424661,1.1273682,-1.2009337,-0.73424661,1.1273681,-1.2009332,-0.73424673,-0.87263215,0.79906696,1.2657533,-0.87263131,-1.2009335,1.2657533,-0.87263179,-1.2009339,1.2657533,1.1273677,0.79906583,1.2657533,1.1273688,0.79906648,-0.73424673,-0.87263167,0.79906696,1.2657533,-0.87263131,0.79906583,1.2657533,1.1273688,0.79906648,-0.73424661,1.1273682,0.79906648,-0.73424661,1.1273682,0.79906583,1.2657533,1.1273688,-1.2009339,1.2657533,1.1273677,-1.2009337,-0.73424661,1.1273681,-1.2009337,-0.73424661,1.1273681,-1.2009339,1.2657533,1.1273677,-1.2009335,1.2657533,-0.87263179,-1.2009332,-0.73424673,-0.87263215,0.79906696,1.2657533,-0.87263131,0.79906648,-0.73424673,-0.87263167,-1.2009332,-0.73424673,-0.87263215,-1.2009335,1.2657533,-0.87263179]
},
"normal" : {
"type" : "Float32Array",
"itemSize" : 3,
"array" : [-1.0658141e-14,-1,5.9604645e-08,-1.0658141e-14,-1,5.9604645e-08,-1.0658141e-14,-1,5.9604645e-08,-1.0658141e-14,-1,5.9604645e-08,0,1,0,0,1,0,0,1,0,0,1,0,1,4.4703416e-08,2.8312209e-07,1,4.4703416e-08,2.8312209e-07,1,4.4703416e-08,2.8312209e-07,1,4.4703416e-08,2.8312209e-07,-2.9802322e-07,-5.9604723e-08,1,-2.9802322e-07,-5.9604723e-08,1,-2.9802322e-07,-5.9604723e-08,1,-2.9802322e-07,-5.9604723e-08,1,-1,-1.1920929e-07,-2.3841858e-07,-1,-1.1920929e-07,-2.3841858e-07,-1,-1.1920929e-07,-2.3841858e-07,-1,-1.1920929e-07,-2.3841858e-07,2.3841858e-07,1.7881393e-07,-1,2.3841858e-07,1.7881393e-07,-1,2.3841858e-07,1.7881393e-07,-1,2.3841858e-07,1.7881393e-07,-1]
},
"index" : {
"type" : "Uint32Array",
"itemSize" : 1,
"array" : [0,1,2,2,3,0,4,5,6,6,7,4,8,9,10,10,11,8,12,13,14,14,15,12,16,17,18,18,19,16,20,21,22,22,23,20]
}
}
}
}],
"materials" : [{
"name" : "Material",
"type" : "MeshBasicMaterial",
"uuid" : "5e847bd4-84a9-5d4b-a8fb-c567e27f7561",
"transparent" : false,
"opacity" : 1,
"color" : 10682379
}]
}, function(object){
that.cube = object;
object.scale.set(50,50,50);
scene.add(object)
});
}
RedCube.prototype.onRender = function(scene, renderer) {
if(this.cube === null) {
this.loadCube(scene, renderer);
}
// Some interprolation logic here to move from lastpos to next pos in average frames
// per tick.
this.cube.position.x = this.x;
}
RedCube.prototype.getType = function() {
return type;
}
RedCube.prototype.generateSyncPacket = function() {
return {
type: this.getType(),
x : this.x
};
}
RedCube.prototype.parseSyncPacket = function(syncpacket) {
this.setPosition(syncpacket.x);
}
RedCube.prototype.generateId = function() {
var d = new Date().getTime();
if (typeof performance !== 'undefined' && typeof performance.now === 'function'){
d += performance.now(); //use high-precision timer if available
}
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
}
RedCube.prototype.getEntityId = function() {
return this.entityId;
}
RedCube.prototype.beforeDeath = function() {
}
RedCube.prototype.die = function() {
}
RedCube.prototype.setPosition = function(newpos) {
this.lastX = this.x;
this.x = newpos;
}
RedCube.prototype.getPosition = function() {
return this.x;
}
RedCube.prototype.getLastX = function() {
return this.lastX;
}
var EntityRegistry = function() {
this.entities = {};
this.types = {};
}
EntityRegistry.prototype.register = function(entity) {
this.entities[entity.getEntityId()] = entity;
}
EntityRegistry.prototype.callUpdate = function() {
for(entityId in this.entities) {
if(this.entities.hasOwnProperty(entityId)) {
this.entities[entityId].onUpdate();
}
}
}
EntityRegistry.prototype.callOnRender = function(scene, renderer) {
for(entityId in this.entities) {
if(this.entities.hasOwnProperty(entityId)) {
this.entities[entityId].onRender(scene, renderer);
}
}
}
EntityRegistry.prototype.remove = function(entity) {
entity.beforeDeath();
delete this.entities[entity.getEntityId()]
entity.die();
}
EntityRegistry.prototype.registerType = function(name, entityClass) {
this.types[name] = entityClass;
}
EntityRegistry.prototype.startEntity = function(syncpacket, entityId) {
var entity = new this.types[syncpacket.type](entityId);
entity.parseSyncPacket(syncpacket);
this.register(entity);
}
EntityRegistry.prototype.getSyncData = function() {
var syncpacket = {};
for(entityId in this.entities) {
if(this.entities.hasOwnProperty(entityId)) {
syncpacket[entityId] = this.entities[entityId].generateSyncPacket();
}
}
return syncpacket;
}
EntityRegistry.prototype.parseSyncData = function(syncpacket) {
for(entityId in syncpacket) {
if(this.entities.hasOwnProperty(entityId)) {
this.entities[entityId].parseSyncPacket(syncpacket[entityId]);
}
else {
this.startEntity(syncpacket[entityId], entityId);
}
}
return syncpacket;
}
var REGISTRY = new EntityRegistry();
REGISTRY.registerType('redcube', RedCube);
var test = "d";
var dx = 1, dy = 0;
var speed = 0.5;
var activeKey = 0;
// Set up the scene, camera, and renderer as global variables.
var scene, camera, renderer;
var worker = new Worker(getInlineJS());
worker.postMessage("dasd");
worker.addEventListener('message', function(e) {
REGISTRY.parseSyncData(e.data);
}, false);
console.log("asd " + test);
init();
animate();
// Sets up the scene.
function init() {
// Create the scene and set the scene size.
scene = new THREE.Scene();
var WIDTH = window.innerWidth - 50,
HEIGHT = 500;
// Create a renderer and add it to the DOM.
renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setSize(WIDTH, HEIGHT);
document.body.appendChild(renderer.domElement);
camera = new THREE.OrthographicCamera( 0, WIDTH, 200, -HEIGHT, 1, 1000 );
camera.position.set(0,0,100);
scene.add(camera);
console.log(WIDTH);
window.addEventListener('resize', function() {
var WIDTH = window.innerWidth - 50,
HEIGHT = window.innerHeight - 50;
renderer.setSize(WIDTH, HEIGHT);
camera.aspect = WIDTH / HEIGHT;
camera.updateProjectionMatrix();
});
renderer.setClearColor();
document.addEventListener('keydown', function(e) {
if (activeKey == e.keyCode) return;
activeKey = e.keyCode;
//left
if (e.keyCode == 37) {
dx = -1;
}
//top
else if (e.keyCode == 38) {
dy = 1;
}
//right
else if (e.keyCode == 39) {
dx = 1;
}
//bottom
else if (e.keyCode == 40) {
dy = -1;
}
});
document.addEventListener('keyup', function(e) {
switch (e.keyCode) {
case 37: // left
case 39: // right
dx = 0;
break;
case 38: // up
case 40: // down
dy = 0;
break;
}
activeKey = 0;
});
}
var start;
var last;
var timefix, oldX,oldY, updateX,updateY,text;
function animate() {
REGISTRY.callOnRender(scene, renderer);
renderer.render(scene, camera);
requestAnimationFrame( animate );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/84/three.js"></script>
<body style="margin: 0;">
<div id="panel">TEST
</div>
<br>
<script type="javascript/worker">
var RedCube = function(id) {
this.direction = false;
this.type = 'redcube';
if(typeof id === 'undefined') {
this.entityId = this.generateId();
}
else {
this.entityId = id;
}
this.lastX = 0;
this.x = 0;
}
RedCube.prototype.getType = function() {
return this.type;
}
RedCube.prototype.generateSyncPacket = function() {
return {
type: this.getType(),
x : this.x
};
}
RedCube.prototype.parseSyncPacket = function(syncpacket) {
this.setPosition(syncpacket.x);
}
RedCube.prototype.generateId = function() {
var d = new Date().getTime();
if (typeof performance !== 'undefined' && typeof performance.now === 'function'){
d += performance.now(); //use high-precision timer if available
}
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
}
RedCube.prototype.getEntityId = function() {
return this.entityId;
}
RedCube.prototype.beforeDeath = function() {
}
RedCube.prototype.die = function() {
}
RedCube.prototype.setPosition = function(newpos) {
this.lastX = this.x;
this.x = newpos;
}
RedCube.prototype.getPosition = function() {
return this.x;
}
RedCube.prototype.getLastX = function() {
return this.lastX;
}
var EntityRegistry = function() {
this.entities = {};
this.types = {};
}
RedCube.prototype.onUpdate = function() {
if(this.x > 500) {
this.direction = true;
}
if(this.x <= 0) {
this.direction = false;
}
this.x += !this.direction ? 20 : -20;
}
RedCube.prototype.onRender = function(scene, renderer) {
/// this is not a rendering thread. leave it empty
}
EntityRegistry.prototype.register = function(entity) {
this.entities[entity.getEntityId()] = entity;
}
EntityRegistry.prototype.remove = function(entity) {
entity.beforeDeath();
delete this.entities[entity.getEntityId()]
entity.die();
}
EntityRegistry.prototype.registerType = function(name, entityClass) {
this.types[name] = entityClass;
}
EntityRegistry.prototype.startEntity = function(entityId, syncpacket) {
var entity = this.types[syncpacket.type](entityId);
entity.parseSyncPacket(syncpacket);
this.register(entity);
}
EntityRegistry.prototype.getSyncData = function() {
var syncpacket = {};
for(entityId in this.entities) {
if(this.entities.hasOwnProperty(entityId)) {
syncpacket[entityId] = this.entities[entityId].generateSyncPacket();
}
}
return syncpacket;
}
EntityRegistry.prototype.callUpdate = function() {
for(entityId in this.entities) {
if(this.entities.hasOwnProperty(entityId)) {
this.entities[entityId].onUpdate();
}
}
}
EntityRegistry.prototype.callOnRender = function(scene, renderer) {
for(entityId in this.entities) {
if(this.entities.hasOwnProperty(entityId)) {
this.entities[entityId].onRender(scene, renderer);
}
}
}
EntityRegistry.prototype.parseSyncData = function(syncpacket) {
for(entityId in syncpacket) {
if(this.entities.hasOwnProperty(entityId)) {
this.entities[entityId].parseSyncPacket(syncpacket[entityid]);
}
else {
this.startEntity(syncpacket, entityId);
}
}
return syncpacket;
}
var REGISTRY = new EntityRegistry();
var little_red = new RedCube();
REGISTRY.register(little_red);
var x = 0;
var timefix = 0;
var last = 0;
var dx = 1;
var loopInterval = 0;
loopInterval = setInterval(function(){
REGISTRY.callUpdate()
var msg = REGISTRY.getSyncData();
self.postMessage(msg);
}, 1000/60);
self.addEventListener('message', function(e) {
}, false);
</script>
</body>

Sometimes white background goes transparent on whole page

I wanted to use this kind of Photo Collage on my Website: Seamless Photo Collage by AutomaticImageMontage
so I downloaded it and pasted the code to my Website..
it works but sometimes when the page loads the white background goes transparent on the whole page transperent background
I'm using Parallax and Bootstrap, sometimes the parallax isn't working properly too.
I have tried to set the background to white in CSS but nothing.. sometimes it loads normally but sometimes goes transparent,
I have checked the console too but it showes only
jquery.montage.min.js:1 Uncaught TypeError: Cannot read property 'apply' of undefined
now i really dont have any idea how to fix it.
please help :(
Javascript CSS and HTML
(function(window, $, undefined) {
Array.max = function(array) {
return Math.max.apply(Math, array)
};
Array.min = function(array) {
return Math.min.apply(Math, array)
};
var $event = $.event,
resizeTimeout;
$event.special.smartresize = {
setup: function() {
$(this).bind("resize", $event.special.smartresize.handler)
},
teardown: function() {
$(this).unbind("resize", $event.special.smartresize.handler)
},
handler: function(event, execAsap) {
var context = this,
args = arguments;
event.type = "smartresize";
if (resizeTimeout) {
clearTimeout(resizeTimeout)
}
resizeTimeout = setTimeout(function() {
jQuery.event.handle.apply(context, args)
}, execAsap === "execAsap" ? 0 : 50)
}
};
$.fn.smartresize = function(fn) {
return fn ? this.bind("smartresize", fn) : this.trigger("smartresize", ["execAsap"])
};
$.fn.imagesLoaded = function(callback) {
var $images = this.find('img'),
len = $images.length,
_this = this,
blank = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
function triggerCallback() {
callback.call(_this, $images)
}
function imgLoaded() {
if (--len <= 0 && this.src !== blank) {
setTimeout(triggerCallback);
$images.unbind('load error', imgLoaded)
}
}
if (!len) {
triggerCallback()
}
$images.bind('load error', imgLoaded).each(function() {
if (this.complete || this.complete === undefined) {
var src = this.src;
this.src = blank;
this.src = src
}
});
return this
};
$.Montage = function(options, element) {
this.element = $(element).show();
this.cache = {};
this.heights = new Array();
this._create(options)
};
$.Montage.defaults = {
liquid: true,
margin: 1,
minw: 70,
minh: 20,
maxh: 250,
alternateHeight: false,
alternateHeightRange: {
min: 100,
max: 300
},
fixedHeight: null,
minsize: false,
fillLastRow: false
};
$.Montage.prototype = {
_getImageWidth: function($img, h) {
var i_w = $img.width(),
i_h = $img.height(),
r_i = i_h / i_w;
return Math.ceil(h / r_i)
},
_getImageHeight: function($img, w) {
var i_w = $img.width(),
i_h = $img.height(),
r_i = i_h / i_w;
return Math.ceil(r_i * w)
},
_chooseHeight: function() {
if (this.options.minsize) {
return Array.min(this.heights)
}
var result = {},
max = 0,
res, val, min;
for (var i = 0, total = this.heights.length; i < total; ++i) {
var val = this.heights[i],
inc = (result[val] || 0) + 1;
if (val < this.options.minh || val > this.options.maxh) continue;
result[val] = inc;
if (inc >= max) {
max = inc;
res = val
}
}
for (var i in result) {
if (result[i] === max) {
val = i;
min = min || val;
if (min < this.options.minh) min = null;
else if (min > val) min = val;
if (min === null) min = val
}
}
if (min === undefined) min = this.heights[0];
res = min;
return res
},
_stretchImage: function($img) {
var prevWrapper_w = $img.parent().width(),
new_w = prevWrapper_w + this.cache.space_w_left,
crop = {
x: new_w,
y: this.theHeight
};
var new_image_w = $img.width() + this.cache.space_w_left,
new_image_h = this._getImageHeight($img, new_image_w);
this._cropImage($img, new_image_w, new_image_h, crop);
this.cache.space_w_left = this.cache.container_w;
if (this.options.alternateHeight) this.theHeight = Math.floor(Math.random() * (this.options.alternateHeightRange.max - this.options.alternateHeightRange.min + 1) + this.options.alternateHeightRange.min)
},
_updatePrevImage: function($nextimg) {
var $prevImage = this.element.find('img.montage:last');
this._stretchImage($prevImage);
this._insertImage($nextimg)
},
_insertImage: function($img) {
var new_w = this._getImageWidth($img, this.theHeight);
if (this.options.minsize && !this.options.alternateHeight) {
if (this.cache.space_w_left <= this.options.margin * 2) {
this._updatePrevImage($img)
} else {
if (new_w > this.cache.space_w_left) {
var crop = {
x: this.cache.space_w_left,
y: this.theHeight
};
this._cropImage($img, new_w, this.theHeight, crop);
this.cache.space_w_left = this.cache.container_w;
$img.addClass('montage')
} else {
var crop = {
x: new_w,
y: this.theHeight
};
this._cropImage($img, new_w, this.theHeight, crop);
this.cache.space_w_left -= new_w;
$img.addClass('montage')
}
}
} else {
if (new_w < this.options.minw) {
if (this.options.minw > this.cache.space_w_left) {
this._updatePrevImage($img)
} else {
var new_w = this.options.minw,
new_h = this._getImageHeight($img, new_w),
crop = {
x: new_w,
y: this.theHeight
};
this._cropImage($img, new_w, new_h, crop);
this.cache.space_w_left -= new_w;
$img.addClass('montage')
}
} else {
if (new_w > this.cache.space_w_left && this.cache.space_w_left < this.options.minw) {
this._updatePrevImage($img)
} else if (new_w > this.cache.space_w_left && this.cache.space_w_left >= this.options.minw) {
var crop = {
x: this.cache.space_w_left,
y: this.theHeight
};
this._cropImage($img, new_w, this.theHeight, crop);
this.cache.space_w_left = this.cache.container_w;
if (this.options.alternateHeight) this.theHeight = Math.floor(Math.random() * (this.options.alternateHeightRange.max - this.options.alternateHeightRange.min + 1) + this.options.alternateHeightRange.min);
$img.addClass('montage')
} else {
var crop = {
x: new_w,
y: this.theHeight
};
this._cropImage($img, new_w, this.theHeight, crop);
this.cache.space_w_left -= new_w;
$img.addClass('montage')
}
}
}
},
_cropImage: function($img, w, h, cropParam) {
var dec = this.options.margin * 2;
var $wrapper = $img.parent('a');
this._resizeImage($img, w, h);
$img.css({
left: -(w - cropParam.x) / 2 + 'px',
top: -(h - cropParam.y) / 2 + 'px'
});
$wrapper.addClass('am-wrapper').css({
width: cropParam.x - dec + 'px',
height: cropParam.y + 'px',
margin: this.options.margin
})
},
_resizeImage: function($img, w, h) {
$img.css({
width: w + 'px',
height: h + 'px'
})
},
_reload: function() {
var new_el_w = this.element.width();
if (new_el_w !== this.cache.container_w) {
this.element.hide();
this.cache.container_w = new_el_w;
this.cache.space_w_left = new_el_w;
var instance = this;
instance.$imgs.removeClass('montage').each(function(i) {
instance._insertImage($(this))
});
if (instance.options.fillLastRow && instance.cache.space_w_left !== instance.cache.container_w) {
instance._stretchImage(instance.$imgs.eq(instance.totalImages - 1))
}
instance.element.show()
}
},
_create: function(options) {
this.options = $.extend(true, {}, $.Montage.defaults, options);
var instance = this,
el_w = instance.element.width();
instance.$imgs = instance.element.find('img');
instance.totalImages = instance.$imgs.length;
if (instance.options.liquid) $('html').css('overflow-y', 'scroll');
if (!instance.options.fixedHeight) {
instance.$imgs.each(function(i) {
var $img = $(this),
img_w = $img.width();
if (img_w < instance.options.minw && !instance.options.minsize) {
var new_h = instance._getImageHeight($img, instance.options.minw);
instance.heights.push(new_h)
} else {
instance.heights.push($img.height())
}
})
}
instance.theHeight = (!instance.options.fixedHeight && !instance.options.alternateHeight) ? instance._chooseHeight() : instance.options.fixedHeight;
if (instance.options.alternateHeight) instance.theHeight = Math.floor(Math.random() * (instance.options.alternateHeightRange.max - instance.options.alternateHeightRange.min + 1) + instance.options.alternateHeightRange.min);
instance.cache.container_w = el_w;
instance.cache.space_w_left = el_w;
instance.$imgs.each(function(i) {
instance._insertImage($(this))
});
if (instance.options.fillLastRow && instance.cache.space_w_left !== instance.cache.container_w) {
instance._stretchImage(instance.$imgs.eq(instance.totalImages - 1))
}
$(window).bind('smartresize.montage', function() {
instance._reload()
})
},
add: function($images, callback) {
var $images_stripped = $images.find('img');
this.$imgs = this.$imgs.add($images_stripped);
this.totalImages = this.$imgs.length;
this._add($images, callback)
},
_add: function($images, callback) {
var instance = this;
$images.find('img').each(function(i) {
instance._insertImage($(this))
});
if (instance.options.fillLastRow && instance.cache.space_w_left !== instance.cache.container_w) instance._stretchImage(instance.$imgs.eq(instance.totalImages - 1));
if (callback) callback.call($images)
},
destroy: function(callback) {
this._destroy(callback)
},
_destroy: function(callback) {
this.$imgs.removeClass('montage').css({
position: '',
width: '',
height: '',
left: '',
top: ''
}).unwrap();
if (this.options.liquid) $('html').css('overflow', '');
this.element.unbind('.montage').removeData('montage');
$(window).unbind('.montage');
if (callback) callback.call()
},
option: function(key, value) {
if ($.isPlainObject(key)) {
this.options = $.extend(true, this.options, key)
}
}
};
var logError = function(message) {
if (this.console) {
console.error(message)
}
};
$.fn.montage = function(options) {
if (typeof options === 'string') {
var args = Array.prototype.slice.call(arguments, 1);
this.each(function() {
var instance = $.data(this, 'montage');
if (!instance) {
logError("cannot call methods on montage prior to initialization; " + "attempted to call method '" + options + "'");
return
}
if (!$.isFunction(instance[options]) || options.charAt(0) === "_") {
logError("no such method '" + options + "' for montage instance");
return
}
instance[options].apply(instance, args)
})
} else {
this.each(function() {
var instance = $.data(this, 'montage');
if (instance) {
instance.option(options || {});
instance._reload()
} else {
$.data(this, 'montage', new $.Montage(options, this))
}
})
}
return this
}
})(window, jQuery);
.am-wrapper{
float:left;
position:relative;
overflow:hidden;
}
.am-wrapper img{
position:absolute;
outline:none;
}
<div class="container">
<div id="am-container" class="am-container"><img src="images/1.jpg"><img src="images/2.jpg"><img src="images/3.jpg"><img src="images/4.jpg"><img src="images/5.jpg"><img src="images/6.jpg"><img src="images/7.jpg"><img src="images/8.jpg"><img src="images/9.jpg"><img src="images/10.jpg"><img src="images/11.jpg"><img src="images/12.jpg"><img src="images/13.jpg"><img src="images/14.jpg"><img src="images/15.jpg"><img src="images/16.jpg"><img src="images/17.jpg"><img src="images/18.jpg"><img src="images/19.jpg">
</div>
</div>
<script type="text/javascript">
$(function() {
var $container = $('#am-container'),
$imgs = $container.find('img').hide(),
totalImgs = $imgs.length,
cnt = 0;
$imgs.each(function(i) {
var $img = $(this);
$('<img/>').load(function() {
++cnt;
if( cnt === totalImgs ) {
$imgs.show();
$container.montage({
fillLastRow : false,
alternateHeight : false,
alternateHeightRange : {
min : 90,
max : 100
}
});
}
}).attr('src',$img.attr('src'));
});
});
</script>

AngularJS $watch within directive not triggering

I have a watch looking at my sliders model and when I want to set one of the properties to visible or enabled it doesn't seem to want to fire the watch changed event. If I click the button it should hide or disable the handle and it does not. If I drag another handle the updateDOM is called and the handle is then hidden or disabled. Not sure what I am doing incorrectly here.
scope.$watch('sliders', function(oldValue, newValue) {
console.log('sliders Update: ', oldValue, ' : ', newValue);
updateDOM();
});
Here is a working plunk: http://plnkr.co/edit/I3A9H8qTs0z4CVaYnyJZ?p=preview
'use strict';
angular.module('angularMultiSlider', [])
.directive('multiSliderKey', function($compile) {
return {
restrict: 'EA',
transclude: true,
scope: {
displayFilter: '#',
sliders : '=ngModel'
},
link: function(scope, element) {
var sliderStr = '';
if (scope.displayFilter === undefined) scope.displayFilter = '';
var filterExpression = scope.displayFilter === '' ? '' : ' | ' + scope.displayFilter;
angular.forEach(scope.sliders, function(slider, key){
var colorKey = slider.color ? '<span style="background-color:' + slider.color + ';"></span> ' : '';
sliderStr += '<div class="key">' + colorKey + '{{ sliders[' + key.toString() + '].title }} <strong>{{ sliders[' + key.toString() + '].value ' + filterExpression + '}}</strong></div>';
});
var sliderControls = angular.element('<div class="angular-multi-slider-key">' + sliderStr + '</div>');
element.append(sliderControls);
$compile(sliderControls)(scope);
}
}
})
.directive('multiSlider', function($compile, $filter) {
var events = {
mouse: {
start: 'mousedown',
move: 'mousemove',
end: 'mouseup'
},
touch: {
start: 'touchstart',
move: 'touchmove',
end: 'touchend'
}
};
function roundStep(value, precision, step, floor) {
var remainder = (value - floor) % step;
var steppedValue = remainder > (step / 2) ? value + step - remainder : value - remainder;
var decimals = Math.pow(10, precision);
var roundedValue = steppedValue * decimals / decimals;
return parseFloat(roundedValue.toFixed(precision));
}
function offset(element, position) {
return element.css({
left: position
});
}
function pixelize(position) {
return parseInt(position) + 'px';
}
function contain(value) {
if (isNaN(value)) return value;
return Math.min(Math.max(0, value), 100);
}
function overlaps(b1, b2, offsetTop) {
function comparePositions(p1, p2) {
var r1 = p1[0] < p2[0] ? p1 : p2;
var r2 = p1[0] < p2[0] ? p2 : p1;
return r1[1] > r2[0] || r1[0] === r2[0];
}
var posB1 = [[ b1.offsetLeft, b1.offsetLeft + b1.offsetWidth ], [ offsetTop, offsetTop - b1.scrollTop + b1.offsetHeight ]],
posB2 = [[ b2.offsetLeft, b2.offsetLeft + b2.offsetWidth ], [ b2.offsetTop, b2.offsetTop - b2.scrollTop + b2.offsetHeight ]];
return comparePositions( posB1[0], posB2[0] ) && comparePositions( posB1[1], posB2[1] );
}
return {
restrict: 'EA',
require: '?ngModel',
scope: {
floor: '#',
ceiling: '#',
step: '#',
precision: '#',
bubbles: '#',
displayFilter: '#',
sliders: '=ngModel'
},
template :
'<div class="bar"></div>',
link: function(scope, element, attrs, ngModel) {
if (!ngModel) return; // do nothing if no ng-model
//base copy to see if sliders returned to original
var original;
ngModel.$render = function() {
original = angular.copy(scope.sliders);
};
element.addClass('angular-multi-slider');
// DOM Components
if (scope.displayFilter === undefined) scope.displayFilter = '';
var filterExpression = scope.displayFilter === '' ? '' : ' | ' + scope.displayFilter;
var sliderStr = '<div class="limit floor">{{ floor ' + filterExpression + ' }}</div>' +
'<div class="limit ceiling">{{ ceiling ' + filterExpression + '}}</div>';
angular.forEach(scope.sliders, function(slider, key){
sliderStr += '<div class="handle"></div><div class="bubble">{{ sliders[' + key.toString() + '].title }}{{ sliders[' + key.toString() + '].value ' + filterExpression + ' }}</div>';
});
var sliderControls = angular.element(sliderStr);
element.append(sliderControls);
$compile(sliderControls)(scope);
var children = element.children();
var bar = angular.element(children[0]),
ngDocument = angular.element(document),
floorBubble = angular.element(children[1]),
ceilBubble = angular.element(children[2]),
bubbles = [],
handles = [];
angular.forEach(scope.sliders, function(slider, key) {
handles.push(angular.element(children[(key * 2) + 3]));
bubbles.push(angular.element(children[(key * 2) + 4]));
});
// Control Dimensions Used for Calculations
var handleHalfWidth = 0,
barWidth = 0,
minOffset = 0,
maxOffset = 0,
minValue = 0,
maxValue = 0,
valueRange = 0,
offsetRange = 0,
bubbleTop = undefined,
bubbleHeight = undefined,
handleTop = undefined,
handleHeight = undefined;
if (scope.step === undefined) scope.step = 10;
if (scope.floor === undefined) scope.floor = 0;
if (scope.ceiling === undefined) scope.ceiling = 500;
if (scope.precision === undefined) scope.precision = 2;
if (scope.bubbles === undefined) scope.bubbles = false;
var bindingsSet = false;
var updateCalculations = function() {
scope.floor = roundStep(parseFloat(scope.floor), parseInt(scope.precision), parseFloat(scope.step), parseFloat(scope.floor));
scope.ceiling = roundStep(parseFloat(scope.ceiling), parseInt(scope.precision), parseFloat(scope.step), parseFloat(scope.floor));
angular.forEach(scope.sliders, function(slider) {
slider.value = roundStep(parseFloat(slider.value), parseInt(scope.precision), parseFloat(scope.step), parseFloat(scope.floor));
});
handleHalfWidth = handles[0][0].offsetWidth / 2;
barWidth = bar[0].offsetWidth;
minOffset = 0;
maxOffset = barWidth - handles[0][0].offsetWidth;
minValue = parseFloat(scope.floor);
maxValue = parseFloat(scope.ceiling);
valueRange = maxValue - minValue;
offsetRange = maxOffset - minOffset;
};
var updateDOM = function () {
updateCalculations();
var percentOffset = function (offset) {
return contain(((offset - minOffset) / offsetRange) * 100);
};
var percentValue = function (value) {
return contain(((value - minValue) / valueRange) * 100);
};
var pixelsToOffset = function (percent) {
return pixelize(percent * offsetRange / 100);
};
var setHandles = function () {
offset(ceilBubble, pixelize(barWidth - ceilBubble[0].offsetWidth));
angular.forEach(scope.sliders, function(slider,key){
if (slider.color) {
handles[key].css({'background-color': slider.color});
}
if (slider.value >= minValue && slider.value <= maxValue) {
offset(handles[key], pixelsToOffset(percentValue(slider.value)));
offset(bubbles[key], pixelize(handles[key][0].offsetLeft - (bubbles[key][0].offsetWidth / 2) + handleHalfWidth));
handles[key].css({'display': 'block'});
if ('' + scope.bubbles === 'true') {
bubbles[key].css({'display': 'block'});
}
} else {
handles[key].css({'display': 'none'});
bubbles[key].css({'display': 'none'});
}
if (slider.hasOwnProperty("visible") && slider.visible === false) {
handles[key].css({'display': 'none'});
bubbles[key].css({'display': 'none'});
}
if (slider.hasOwnProperty("enabled") && slider.enabled === false) {
handles[key].addClass('disabled');
bubbles[key].addClass('disabled');
} else {
handles[key].removeClass('disabled');
bubbles[key].removeClass('disabled');
}
});
};
var resetBubbles = function() {
if (scope.sliders.length > 1) {
//timeout must be longer than css animation for proper bubble collision detection
for (var i = 0; i < scope.sliders.length; i++) {
(function (index) {
setTimeout(function () {
overlapCheck(index);
}, i * 150);
})(i);
}
}
};
var overlapCheck = function(currentRef) {
var safeAtLevel = function(cRef, level) {
for (var x = 0; x < scope.sliders.length; x++) {
if (x != cRef && overlaps(bubbles[cRef][0], bubbles[x][0], (bubbleTop * level))) {
return safeAtLevel(cRef, level + 1);
}
}
return level;
};
if (scope.sliders.length > 1) {
var safeLevel = safeAtLevel(currentRef, 1) - 1;
handles[currentRef].css({top: pixelize((-1 * (safeLevel * bubbleHeight)) + handleTop), height: pixelize(handleHeight + (bubbleHeight * safeLevel)), 'z-index': 99-safeLevel});
bubbles[currentRef].css({top: pixelize(bubbleTop - (bubbleHeight * safeLevel))});
}
};
var bind = function (handle, bubble, currentRef, events) {
var onEnd = function () {
handle.removeClass('grab');
bubble.removeClass('grab');
if (!(''+scope.bubbles === 'true')) {
bubble.removeClass('active');
}
ngDocument.unbind(events.move);
ngDocument.unbind(events.end);
if (angular.equals(scope.sliders, original)) {
ngModel.$setPristine();
}
//Move possible elevated bubbles back down if one below it moved.
resetBubbles();
scope.$apply();
};
var onMove = function (event) {
// Suss out which event type we are capturing and get the x value
var eventX = 0;
if (event.clientX !== undefined) {
eventX = event.clientX;
}
else if ( event.touches !== undefined && event.touches.length) {
eventX = event.touches[0].clientX;
}
else if ( event.originalEvent !== undefined &&
event.originalEvent.changedTouches !== undefined &&
event.originalEvent.changedTouches.length) {
eventX = event.originalEvent.changedTouches[0].clientX;
}
var newOffset = Math.max(Math.min((eventX - element[0].getBoundingClientRect().left - handleHalfWidth), maxOffset), minOffset),
newPercent = percentOffset(newOffset),
newValue = minValue + (valueRange * newPercent / 100.0);
newValue = roundStep(newValue, parseInt(scope.precision), parseFloat(scope.step), parseFloat(scope.floor));
scope.sliders[currentRef].value = newValue;
setHandles();
overlapCheck(currentRef);
ngModel.$setDirty();
scope.$apply();
};
var onStart = function (event) {
if (scope.sliders[currentRef].hasOwnProperty("enabled") && scope.sliders[currentRef].enabled === false) {
bubble.addClass('disabled');
handle.addClass('disabled');
return;
}
updateCalculations();
bubble.addClass('active grab');
handle.addClass('active grab');
setHandles();
event.stopPropagation();
event.preventDefault();
ngDocument.bind(events.move, onMove);
return ngDocument.bind(events.end, onEnd);
};
handle.bind(events.start, onStart);
};
var setBindings = function () {
var method, i;
var inputTypes = ['touch', 'mouse'];
for (i = 0; i < inputTypes.length; i++) {
method = inputTypes[i];
angular.forEach(scope.sliders, function(slider, key){
bind(handles[key], bubbles[key], key, events[method]);
if (scope.sliders[key].hasOwnProperty("enabled") && scope.sliders[key].enabled === false) {
handles[key].addClass('disabled');
bubbles[key].addClass('disabled');
}
});
}
bindingsSet = true;
};
if (!bindingsSet) {
setBindings();
// Timeout needed because bubbles offsetWidth is incorrect during initial rendering of html elements
setTimeout( function() {
if ('' + scope.bubbles === 'true') {
angular.forEach(bubbles, function (bubble) {
bubble.addClass('active');
});
}
updateCalculations();
setHandles();
//Get Default sizes of bubbles and handles, assuming each are equal, calculated from css
handleTop = handleTop === undefined ? handles[0][0].offsetTop : handleTop;
handleHeight = handleHeight === undefined ? handles[0][0].offsetHeight : handleHeight;
bubbleTop = bubbleTop === undefined ? bubbles[0][0].offsetTop : bubbleTop;
bubbleHeight = bubbleHeight === undefined ? bubbles[0][0].offsetHeight + 7 : bubbleHeight ; //add 7px bottom margin to the bubble offset for handle
resetBubbles();
}, 10);
}
};
// Watch Models based on mode
scope.$watch('sliders', function(oldValue, newValue) {
console.log('sliders Update: ', oldValue, ' : ', newValue);
updateDOM();
});
scope.$watch('ceiling', function() {
bindingsSet = false;
updateDOM();
});
scope.$watch('floor', function() {
bindingsSet = false;
updateDOM();
});
// Update on Window resize
window.addEventListener('resize', updateDOM);
}
}
});
I found the solution here: How to deep watch an array in angularjs? Deep watch /property watch.
$scope.$watch('columns', function() {
// some value in the array has changed
}, true); // watching properties

Jquery stopped working

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.

Categories

Resources