I'm trying to create a slider and one of its function is being able to be move to next and previous by mouse event.
It is already working but the problem is that when it reaches the end, it keeps scrolling. Here is my JSfiddle.
Any idea?
var sliding,
dir,
startClientX = 0,
prevClientX = 0,
$mainDiv = $('#main-div');
function move(dir, step) {
var $ul = $mainDiv.find('.slider'),
liWidth = $ul.find('div').width();
$ul.animate({
left: '+=' + (dir * liWidth)
}, 200);
}
$mainDiv.mousedown(function (event) {
sliding = true;
startClientX = event.clientX;
return false;
}).mouseup(function (event) {
var step = event.clientX - startClientX,
dir = step > 0 ? 1 : -1;
step = Math.abs(step);
move(dir, step);
});
Instead of writing custom javascript code, I would suggest going for using jQuery cycle2 plugin that will make your life easier.
http://jquery.malsup.com/cycle2/
Demo
You need to check if slider reached left or not;
var sliding,
dir,
startClientX = 0,
prevClientX = 0,
$mainDiv = $('#main-div');
function move(dir, step) {
var $ul = $mainDiv.find('.slider'),
liWidth = $ul.find('div').width();
var childCount = $(".slider div").length;
if (((childCount - 1) * liWidth + getLeftPos()) <= 0) {
return false;
}
$ul.animate({
left: '+=' + (dir * liWidth)
}, 200);
}
function getLeftPos() {
var childPos = $(".slider").offset();
var parentPos = $(".slider").parent().offset();
return (childPos.left - parentPos.left);
}
$mainDiv.mousedown(function (event) {
sliding = true;
startClientX = event.clientX;
return false;
}).mouseup(function (event) {
var step = event.clientX - startClientX,
dir = step > 0 ? 1 : -1;
step = Math.abs(step);
move(dir, step);
});
Related
I am using cards list with links and it is scrollable horizontally using mouse as well as arrows.
I Want to prevent clicking ( tags) while scrolling/dragging items left or right.
But clicking should work if i am not dragging items.
Here is what I am using in Javascript.
Code
var instance = $(".hs__wrapper");
$.each( instance, function(key, value)
{
var arrows = $(instance[key]).find(".arrow"),
prevArrow = arrows.filter('.arrow-prev'),
nextArrow = arrows.filter('.arrow-next'),
box = $(instance[key]).find(".hs"),
x = 0,
mx = 0,
maxScrollWidth = box[0].scrollWidth - (box[0].clientWidth / 2) - (box.width() / 2);
$(arrows).on('click', function() {
if ($(this).hasClass("arrow-next")) {
x = ((box.width() / 2)) + box.scrollLeft() - 10;
box.animate({
scrollLeft: x,
})
} else {
x = ((box.width() / 2)) - box.scrollLeft() -10;
box.animate({
scrollLeft: -x,
})
}
});
$(box).on({
mousemove: function(e) {
var mx2 = e.pageX - this.offsetLeft;
if(mx) this.scrollLeft = this.sx + mx - mx2;
},
mousedown: function(e) {
this.sx = this.scrollLeft;
mx = e.pageX - this.offsetLeft;
},
scroll: function() {
toggleArrows();
}
});
$(document).on("mouseup", function(){
mx = 0;
});
function toggleArrows() {
if(box.scrollLeft() > maxScrollWidth - 10) {
// disable next button when right end has reached
nextArrow.addClass('disabled');
} else if(box.scrollLeft() < 10) {
// disable prev button when left end has reached
prevArrow.addClass('disabled')
} else{
// both are enabled
nextArrow.removeClass('disabled');
prevArrow.removeClass('disabled');
}
}
});
Try adding a click event handler to the links which prevents default browser behaviour while scrolling. Then, remove the event handler, detecting when scrolling stops using e.g. this method.
var instance = $(".hs__wrapper");
$.each( instance, function(key, value)
{
var arrows = $(instance[key]).find(".arrow"),
prevArrow = arrows.filter('.arrow-prev'),
nextArrow = arrows.filter('.arrow-next'),
box = $(instance[key]).find(".hs"),
x = 0,
mx = 0,
maxScrollWidth = box[0].scrollWidth - (box[0].clientWidth / 2) - (box.width() / 2);
$(arrows).on('click', function() {
if ($(this).hasClass("arrow-next")) {
x = ((box.width() / 2)) + box.scrollLeft() - 10;
box.animate({
scrollLeft: x,
})
} else {
x = ((box.width() / 2)) - box.scrollLeft() -10;
box.animate({
scrollLeft: -x,
})
}
});
$(box).on({
mousemove: function(e) {
var mx2 = e.pageX - this.offsetLeft;
if(mx) this.scrollLeft = this.sx + mx - mx2;
},
mousedown: function(e) {
this.sx = this.scrollLeft;
mx = e.pageX - this.offsetLeft;
},
scroll: function() {
clearTimeout($.data(this, 'scrollTimer'));
$.data(this, 'scrollTimer', setTimeout(function() {
$(box).find('a').off('click');
}, 250));
toggleArrows();
$(box).find('a').on('click', function(e) {
e.preventDefault();
});
}
});
$(document).on("mouseup", function(){
mx = 0;
});
function toggleArrows() {
if(box.scrollLeft() > maxScrollWidth - 10) {
// disable next button when right end has reached
nextArrow.addClass('disabled');
} else if(box.scrollLeft() < 10) {
// disable prev button when left end has reached
prevArrow.addClass('disabled')
} else{
// both are enabled
nextArrow.removeClass('disabled');
prevArrow.removeClass('disabled');
}
}
});
Seen a few similar questions on here but most seem to refer to zooming and panning images, I can't find anything that answers my problem.
I'm looking to create something like https://timmywil.com/panzoom/demo/, but I want to have a DOM element zoom on click, then pan around on mouse move.
I've been able to come up with something that's very nearly there, example here. https://jsfiddle.net/kevngibsn/5okxr8n3/29/
For this I'm using Zoomooz to handle the zoom, and jQuery Pan to take care of the panning. The issue with this example is that jQuery Pan works out the size of the DOM element on page load and doesn't take into account the increased size after zoom, so mouse move doesn't pan to the edges.
Here's the code from jQuery Pan:
(function( $ ){
var getSize = function($element) {
return {
'width': $element.width(),
'height': $element.height()
};
};
var toCoords = function(x, y) {
return {'x': x, 'y': y};
};
var vectorsEqual = function(v1, v2) {
return v1.x == v2.x && v1.y == v2.y;
}
$.fn.pan = function(options) {
//Container is element this plugin is applied to;
//we're pan it's child element, content
var container = this;
var content = this.children(':first');
//Precalculate the limits of panning - offset stores
//the current amount of pan throughout
var offset = toCoords(
Number(content.css('left').replace('px', '')) | 0,
Number(content.css('top').replace('px', '')) | 0
);
var containerSize = getSize(container);
var contentSize = getSize(content);
var minOffset = toCoords(
-contentSize.width + containerSize.width,
-contentSize.height + containerSize.height
);
var maxOffset = toCoords(0, 0);
//By default, assume mouse sensitivity border
//is 25% of the smallest dimension
var defaultMouseEdge = 0.25 * Math.min(
containerSize.width,
containerSize.height
);
var settings = $.extend( {
'autoSpeedX' : 0,
'autoSpeedY' : 0,
'mouseControl' : 'kinetic',
'kineticDamping' : 0.8,
'mouseEdgeSpeed' : 5,
'mouseEdgeWidth' : defaultMouseEdge,
'proportionalSmoothing' : 0.5,
'updateInterval' : 50,
'mousePan' : null
}, options);
//Mouse state variables, set by bound mouse events below
var mouseOver = false;
var mousePanningDirection = toCoords(0, 0);
var mousePosition = toCoords(0, 0);
var dragging = false;
var lastMousePosition = null;
var kineticVelocity = toCoords(0, 0);
//Delay in ms between updating position of content
var updateInterval = settings.updateInterval;
var onInterval = function() {
if (container.hasClass('pan-off')) return false; //Temporarily disabling pan add/remove class pan-off
var mouseControlHandlers = {
'edge' : updateEdge,
'proportional' : updateProportional,
'kinetic' : updateKinetic
};
var currentHandler = settings.mouseControl;
if(!mouseControlHandlers[currentHandler]()) {
//The handler isn't active - just pan normally
offset.x += settings.autoSpeedX;
offset.y += settings.autoSpeedY;
}
//If the previous updates have take the content
//outside the allowed min/max, bring it back in
constrainToBounds();
//If we're panning automatically, make sure we're
//panning in the right direction if the content has
//moved as far as it can go
if(offset.x == minOffset.x) settings.autoSpeedX = Math.abs(settings.autoSpeedX);
if(offset.x == maxOffset.x) settings.autoSpeedX = -Math.abs(settings.autoSpeedX);
if(offset.y == minOffset.y) settings.autoSpeedY = Math.abs(settings.autoSpeedY);
if(offset.y == maxOffset.y) settings.autoSpeedY = -Math.abs(settings.autoSpeedY);
//Finally, update the position of the content
//with our carefully calculated value
content.css('left', offset.x + "px");
content.css('top', offset.y + "px");
}
var updateEdge = function() {
if(!mouseOver) return false;
//The user's possibly maybe mouse-navigating,
//so we'll find out what direction in case we need
//to handle any callbacks
var newDirection = toCoords(0, 0);
//If we're in the interaction zones to either
//end of the element, pan in response to the
//mouse position.
if(mousePosition.x < settings.mouseEdgeWidth) {
offset.x += settings.mouseEdgeSpeed;
newDirection.x = -1;
}
if (mousePosition.x > containerSize.width - settings.mouseEdgeWidth) {
offset.x -= settings.mouseEdgeSpeed;
newDirection.x = 1;
}
if(mousePosition.y < settings.mouseEdgeWidth) {
offset.y += settings.mouseEdgeSpeed;
newDirection.y = -1;
}
if (mousePosition.y > containerSize.height - settings.mouseEdgeWidth) {
offset.y -= settings.mouseEdgeSpeed;
newDirection.y = 1;
}
updateMouseDirection(newDirection);
return true;
}
var updateProportional = function() {
if(!mouseOver) return false;
var rx = mousePosition.x / containerSize.width;
var ry = mousePosition.y / containerSize.height;
targetOffset = toCoords(
(minOffset.x - maxOffset.x) * rx + maxOffset.x,
(minOffset.y - maxOffset.y) * ry + maxOffset.y
);
var damping = 1 - settings.proportionalSmoothing;
offset = toCoords(
(targetOffset.x - offset.x) * damping + offset.x,
(targetOffset.y - offset.y) * damping + offset.y
)
return true;
}
var updateKinetic = function() {
if(dragging) {
if(lastMousePosition == null) {
lastMousePosition = toCoords(mousePosition.x, mousePosition.y);
}
kineticVelocity = toCoords(
mousePosition.x - lastMousePosition.x,
mousePosition.y - lastMousePosition.y
);
lastMousePosition = toCoords(mousePosition.x, mousePosition.y);
}
offset.x += kineticVelocity.x;
offset.y += kineticVelocity.y;
kineticVelocity = toCoords(
kineticVelocity.x * settings.kineticDamping,
kineticVelocity.y * settings.kineticDamping
);
//If the kinetic velocity is still greater than a small threshold, this
//function is still controlling movement so we return true so autopanning
//doesn't interfere.
var speedSquared = Math.pow(kineticVelocity.x, 2) + Math.pow(kineticVelocity.y, 2);
return speedSquared > 0.01
}
var constrainToBounds = function() {
if(offset.x < minOffset.x) offset.x = minOffset.x;
if(offset.x > maxOffset.x) offset.x = maxOffset.x;
if(offset.y < minOffset.y) offset.y = minOffset.y;
if(offset.y > maxOffset.y) offset.y = maxOffset.y;
}
var updateMouseDirection = function(newDirection) {
if(!vectorsEqual(newDirection, mousePanningDirection)) {
mousePanningDirection = newDirection;
if(settings.mousePan) {
settings.mousePan(mousePanningDirection);
}
}
}
this.bind('mousemove', function(evt) {
mousePosition.x = evt.pageX - container.offset().left;
mousePosition.y = evt.pageY - container.offset().top;
mouseOver = true;
});
this.bind('mouseleave', function(evt) {
mouseOver = false;
dragging = false;
lastMousePosition = null;
updateMouseDirection(toCoords(0, 0));
});
this.bind('mousedown', function(evt) {
dragging = true;
return false; //Prevents FF from thumbnailing & dragging
});
this.bind('mouseup', function(evt) {
dragging = false;
lastMousePosition = null;
});
//Kick off the main panning loop and return
//this to maintain jquery chainability
setInterval(onInterval, updateInterval);
return this;
};
})( jQuery );
I'd at about my limit on this one, any advice on how to get that panning the whole element?
I built a magnifying glass in JavaScript, which works well when I click on it or click and dragging it, but it should not hide from the screen.
$(".menu-left-preview-box-preview").bind('click', function (e) {
window.location = "page" + ($(this).index() + 1) + ".html";
});
var native_width = 0;
var native_height = 0;
var magnifyIsMouseDown = false;
$(".magnify").parent().mousedown(function (e) {
magnifyIsMouseDown = true;
});
$(".magnify").mousemove(function (e) {
if (magnifyIsMouseDown) {
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 = $(this).offset();
var mx = e.pageX - magnify_offset.left;
var my = e.pageY - magnify_offset.top;
if (mx < $(this).width() && my < $(this).height() && mx > 0 && my > 0) {
$(".large").fadeIn(100);
} else {
$(".large").fadeOut(100);
}
if ($(".large").is(":visible")) {
var rx = Math.round(mx / $(".small").width() * native_width - $(".large").width() / 2) * -1;
var ry = Math.round(my / $(".small").height() * native_height - $(".large").height() / 2) * -1;
var bgp = rx + "px " + ry + "px";
var px = mx - $(".large").width() / 2;
var py = my - $(".large").height() / 2;
$(".large").css({ left: px, top: py, backgroundPosition: bgp });
}
}
}
});
$(".magnify").parent().mouseup(function (e) {
magnifyIsMouseDown = false;
$(".large").fadeOut(100);
});
$(".magnify").parent().mouseleave(function (e) {
$(".large").fadeOut(100);
});
manageSlide();
By default the magnifying glass must be there on the screen. The magnifying glass can be dragged and after it's dropped it must remain there at it's dropped position.
On clicking and dragging the magnify glass is working well, but it should not hide from the screen. It should be there on screen.
Provide handle of magnify glass with that circle (in design).
Working example: http://jsfiddle.net/mohsin80/4ww8efx5/
I replaced the if (magnifyIsMouseDown) { by if (isDragging) { and created the following methods:
var isDragging = false;
$(".magnify").parent().mouseup(function(e) {
isDragging = false;
});
$(".magnify").parent().mousedown(function(e) {
isDragging = true;
});
To make a simulated drag event with jQuery.
Here is the fiddle. Hope it helped :)
I'm attempting to output on a page multiple 'labels' over an image using absolute positioned divs. Each of these divs has a unique number and are placed according to an x and y position on the map (these are percentage based so the image may be scaled).
As some of these labels may overlap, I need a way to either stop them from overlapping, or to essentially 'bump' them off eachother so they no longer overlap. (At this point, it doesn't matter if they are not in their correct position as long as they are near enough as there is a separate 'Pin' view).
They need to stay within the confines of their container and not overlap with eachother.
HTML:
<div id="labelzone">
<div class="label" style="left:0%;top:8%">001</div>
<div class="label" style="left:0%;top:11%">002</div>
<div class="label" style="left:1%;top:10%">003</div>
</div>
CSS:
#labelzone{
float:left;
width:500px;
height:500px;
border: 1px solid black;
position: relative;
}
.label{
position:absolute;
border:1px solid black;
background-color:white;
}
Jsfiddle: https://jsfiddle.net/79cco1oy/
There's a simple example of what I have as an output, these pins could be placed anywhere and there is no limit to how many is on the page, however there shouldn't be any occasion where there are too many to fit in the area.
I'm toying around with doing some form of collision detection and currently attempting to figure out an algorithm of some sort to get them to no longer overlap, and ensure they also don't overlap another item.
My solution is a bit more object oriented.
One object (LabelPool) will contain labels and will be in charge of storing and accomodating them so that they don't collide. You can customize the x/y values that you want to add/substract of the Label's positions in order to avoid their collision. The other object (Label) defines a Label and has some convenient methods. The collision algorithm that I used in LabelPool was taken from this post
var Label = function ($el) {
var position = $el.position(),
width = $el.outerWidth(true),
height = $el.outerHeight(true);
this.getRect = function () {
return {
x: position.left,
y: position.top,
width: width,
height: height
};
};
this.modifyPos = function (modX, modY) {
position.top += modY;
position.left += modX;
updatePos();
};
function updatePos() {
$el.css({
top: position.top,
left: position.left
});
}
};
var LabelPool = function () {
var labelPool = [];
function collides(a, b) {
return !(((a.y + a.height) < (b.y)) || (a.y > (b.y + b.height)) || ((a.x + a.width) < b.x) || (a.x > (b.x + b.width)));
}
function overlaps(label) {
var a = label.getRect();
return labelPool.some(function (other) {
return collides(a, other.getRect());
});
}
this.accomodate = function (label) {
while (labelPool.length && overlaps(label)) {
label.modifyPos(0, 1);// You can modify these values as you please.
}
labelPool.push(label);
};
};
var labelPool = new LabelPool;
$(".label").each(function (_, el) {
labelPool.accomodate(new Label($(el)));
});
Here's the fiddle.
Hope it helps.
Using js and jquery, you can find a basic collision engine based on left/top abs position and size of the label.
https://jsfiddle.net/Marcassin/79cco1oy/6/
Every time you want to add a Label, you check if the positionning is overlaping any existing div, in this case, you translate the new Label to position. This operation may not be the most beautiful you can find, there can be a long process time in case of lots of labels.
$(document).ready (function () {
addLabel (0, 8);
addLabel (0, 11);
addLabel (1, 10);
addLabel (2, 7);
});
function addLabel (newLeft, newTop)
{
var newLab = document.createElement ("div");
newLab.className = "label";
$(newLab).css({"left": newLeft+"%", "top": newTop + "%"});
var labels = $("#labelzone > div");
newLab.innerHTML = "00" + (labels.length + 1); // manage 0s
$("#labelzone").append (newLab);
var isCollision = false;
var cpt = 1;
do
{
isCollision = false;
$(labels).each (function () {
if (! isCollision && collision (this, newLab))
isCollision = true;
});
if (isCollision)
$(newLab).css({"left": (newLeft + cpt++) + "%",
"top": (newTop + cpt++) + "%"});
} while (isCollision);
}
function isInside (pt, div)
{
var x = parseInt($(div).css("left"));
var y = parseInt($(div).css("top"));
var w = $(div).width () + borderWidth;
var h = $(div).height ();
if (pt[0] >= x && pt[0] <= x + w &&
pt[1] >= y && pt[1] <= y + h)
return true;
return false;
}
function collision (div1, div2)
{
var x = parseInt($(div1).css("left"));
var y = parseInt($(div1).css("top"));
var w = $(div1).width () + borderWidth;
var h = $(div1).height ();
var pos = [x, y];
if (isInside (pos, div2))
return true;
pos = [x + w, y];
if (isInside (pos, div2))
return true;
pos = [x + w, y + h];
if (isInside (pos, div2))
return true;
pos = [x, y + h];
if (isInside (pos, div2))
return true;
return false;
}
Here's another implementation of collision detection close to what you asked for. The two main goals being:
move vertically more than horizontally (because boxes are wider than tall)
stay within a reasonable range from the origin
Here goes:
function yCollision($elem) {
var $result = null;
$('.label').each(function() {
var $candidate = $(this);
if (!$candidate.is($elem) &&
$candidate.position().top <= $elem.position().top + $elem.outerHeight() &&
$candidate.position().top + $candidate.outerHeight() >= $elem.position().top) {
$result = $candidate;
console.log("BUMP Y");
}
});
return $result;
}
function xCollision($elem) {
var $result = null;
$('.label').each(function() {
$candidate = $(this);
if (!$candidate.is($elem) &&
yCollision($elem) &&
yCollision($elem).is($candidate) &&
$candidate.position().left <= $elem.position().left + $elem.outerWidth() &&
$candidate.position().left + $candidate.outerWidth() >= $elem.position().left) {
$result = $candidate;
console.log("BUMP X");
}
});
return $result;
}
function fuzzyMoveY($elem, direction) {
var newTop = $elem.position().top + $elem.outerHeight() / 4 * direction;
// stay in the canvas - top border
newTop = (newTop < 0 ? 0 : newTop);
// stay in the canvas - bottom border
newTop = (newTop + $elem.outerHeight() > $("#labelzone").outerHeight() ? $("#labelzone").outerHeight() - $elem.outerHeight() : newTop);
// stay close to our origin
newTop = (Math.abs(newTop - $elem.attr("data-origin-top")) > $elem.outerHeight() ? $elem.attr("data-origin-top") : newTop);
$elem.css({'top': newTop});
}
function fuzzyMoveX($elem, direction) {
var newLeft = $elem.position().left + $elem.outerWidth() / 4 * direction;
// stay in the canvas - left border
newLeft = (newLeft < 0 ? 0 : newLeft);
// stay in the canvas - right border
newLeft = (newLeft + $elem.outerWidth() > $("#labelzone").outerWidth() ? $("#labelzone").outerWidth() - $elem.outerWidth() : newLeft);
// stay close to our origin
newLeft = (Math.abs(newLeft - $elem.attr("data-origin-left")) > $elem.outerWidth() ? $elem.attr("data-origin-left") : newLeft);
$elem.css({'left': newLeft});
}
function bumpY($above, $below) {
if ($above.position().top > $below.position().top) {
$buff = $above;
$above = $below;
$below = $buff;
}
fuzzyMoveY($above, -1);
fuzzyMoveY($below, 1);
}
function bumpX($left, $right) {
if ($left.position().left > $right.position().left) {
$buff = $right;
$right = $left;
$left = $buff;
}
fuzzyMoveX($left, 1);
fuzzyMoveX($right, -1);
}
$('.label').each(function() {
$(this).attr('data-origin-left', $(this).position().left);
$(this).attr('data-origin-top', $(this).position().top);
});
var yShallPass = true;
var loopCount = 0;
while (yShallPass && loopCount < 10) {
yShallPass = false;
$('.label').each(function() {
var $this = $(this);
$collider = yCollision($this);
if ($collider) {
bumpY($this, $collider);
yShallPass = true;
}
});
loopCount++;
}
console.log("y loops", loopCount);
var xShallPass = true;
var loopCount = 0;
while (xShallPass && loopCount < 10) {
xShallPass = false;
$('.label').each(function() {
var $this = $(this);
$collider = xCollision($this);
if ($collider) {
bumpX($this, $collider);
xShallPass = true;
}
});
loopCount++;
}
console.log("x loops", loopCount);
This is not production code obviously but please report back if it helps.
I'm following this tutorial to build a mobile slider: http://mobile.smashingmagazine.com/2012/06/21/play-with-hardware-accelerated-css/
The only difference is, I'm trying to incorporate it into Backbone. However, I've run into a variable problem. Can anyone offer some advice as to how to get this to work. Passing these variables throughout the View's functions is the problem:
var sliding = startClientX = startPixelOffset = pixelOffset = currentSlide = 0,
slideCount = $('.slide').length;
Full Backbone View:
WhiteDeals.Views.EditorView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render', 'slideStart', 'slide');
var sliding = startClientX = startPixelOffset = pixelOffset = currentSlide = 0,
slideCount = $('#dealSlide').length;
},
events: {
"touchstart" : "slideStart",
"mousedown" : "slideStart",
"mouseup" : "slideEnd",
"touchend" : "slideEnd",
"mousemove" : "slide",
"touchmove" : "slide"
},
slideStart: function(event) {
if (event.originalEvent.touches)
event = event.originalEvent.touches[0];
if (sliding == 0) {
sliding = 1;
startClientX = event.clientX;
}
}, // End slideStart
slide: function(event) {
event.preventDefault();
if (event.originalEvent.touches)
event = event.originalEvent.touches[0];
var deltaSlide = event.clientX - startClientX;
if (sliding == 1 && deltaSlide != 0) {
sliding = 2;
startPixelOffset = pixelOffset;
}
if (sliding == 2) {
var touchPixelRatio = 1;
if ((currentSlide == 0 && event.clientX > startClientX) ||
(currentSlide == slideCount - 1 && event.clientX < startClientX))
touchPixelRatio = 3;
pixelOffset = startPixelOffset + deltaSlide / touchPixelRatio;
$('#dealSlider').css('transform', 'translate3d(' + pixelOffset + 'px,0,0)').removeClass();
}
},
slideEnd: function(event) {
if (sliding == 2) {
sliding = 0;
currentSlide = pixelOffset < startPixelOffset ? currentSlide + 1 : currentSlide - 1;
currentSlide = Math.min(Math.max(currentSlide, 0), slideCount - 1);
pixelOffset = currentSlide * -$('body').width();
$('#temp').remove();
$('<style id="temp">#dealSlider.animate{transform:translate3d(' + pixelOffset + 'px,0,0)}</style>').appendTo('head');
$('#dealSlider').addClass('animate').css('transform', '');
}
}, // End slideEnd
render: function() {
this.$el.html(JST['editor/view']());
return this;
}
}); // End of Views EditorView
I would pack those variable into a model, like:
var CoordsModel = Backbone.Model.extend({})
var coord = new CoordsModel();
then pass it to the WhiteDeals view:
var view = new WhiteDeals({model: coord});
then accros all functions, through models' getters/setter I have access to its variables, for example:
initialize: function() {
_.bindAll(this, 'render', 'slideStart', 'slide');
// var sliding = startClientX = startPixelOffset = pixelOffset = currentSlide = 0
this.model.set('sliding', 0);
this.model.set('startClientX', 0);
...
this.model.set('currentSlide', 0);
slideCount = $('#dealSlide').length;
},
...
slideStart: function(event) {
if (event.originalEvent.touches)
event = event.originalEvent.touches[0];
if (sliding == 0) {
// sliding = 1;
// startClientX = event.clientX;
this.model.set('sliding', 1);
this.model.set('startClientX', event.clientX);
}
}, // End slideStart