How to prevent click while scrolling horizontally - javascript

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');
}
}
});

Related

How to use event listeners to make click, drag, and drop function? [duplicate]

Im struggling with seemingly a simple javascript exercise, writing a vanilla drag and drop. I think Im making a mistake with my 'addeventlisteners', here is the code:
var ele = document.getElementsByClassName ("target")[0];
var stateMouseDown = false;
//ele.onmousedown = eleMouseDown;
ele.addEventListener ("onmousedown" , eleMouseDown , false);
function eleMouseDown () {
stateMouseDown = true;
document.addEventListener ("onmousemove" , eleMouseMove , false);
}
function eleMouseMove (ev) {
do {
var pX = ev.pageX;
var pY = ev.pageY;
ele.style.left = pX + "px";
ele.style.top = pY + "px";
document.addEventListener ("onmouseup" , eleMouseUp , false);
} while (stateMouseDown === true);
}
function eleMouseUp () {
stateMouseDown = false;
document.removeEventListener ("onmousemove" , eleMouseMove , false);
document.removeEventListener ("onmouseup" , eleMouseUp , false);
}
Here's a jsfiddle with it working: http://jsfiddle.net/fpb7j/1/
There were 2 main issues, first being the use of onmousedown, onmousemove and onmouseup. I believe those are only to be used with attached events:
document.body.attachEvent('onmousemove',drag);
while mousedown, mousemove and mouseup are for event listeners:
document.body.addEventListener('mousemove',drag);
The second issue was the do-while loop in the move event function. That function's being called every time the mouse moves a pixel, so the loop isn't needed:
var ele = document.getElementsByClassName ("target")[0];
ele.addEventListener ("mousedown" , eleMouseDown , false);
function eleMouseDown () {
stateMouseDown = true;
document.addEventListener ("mousemove" , eleMouseMove , false);
}
function eleMouseMove (ev) {
var pX = ev.pageX;
var pY = ev.pageY;
ele.style.left = pX + "px";
ele.style.top = pY + "px";
document.addEventListener ("mouseup" , eleMouseUp , false);
}
function eleMouseUp () {
document.removeEventListener ("mousemove" , eleMouseMove , false);
document.removeEventListener ("mouseup" , eleMouseUp , false);
}
By the way, I had to make the target's position absolute for it to work.
you can try this fiddle too, http://jsfiddle.net/dennisbot/4AH5Z/
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>titulo de mi pagina</title>
<style>
#target {
width: 100px;
height: 100px;
background-color: #ffc;
border: 2px solid blue;
position: absolute;
}
</style>
<script>
window.onload = function() {
var el = document.getElementById('target');
var mover = false, x, y, posx, posy, first = true;
el.onmousedown = function() {
mover = true;
};
el.onmouseup = function() {
mover = false;
first = true;
};
el.onmousemove = function(e) {
if (mover) {
if (first) {
x = e.offsetX;
y = e.offsetY;
first = false;
}
posx = e.pageX - x;
posy = e.pageY - y;
this.style.left = posx + 'px';
this.style.top = posy + 'px';
}
};
}
</script>
</head>
<body>
<div id="target" style="left: 10px; top:20px"></div>
</body>
</html>
I've just made a simple drag.
It's a one liner usage, and it handles things like the offset of the mouse to the top left corner of the element, onDrag/onStop callbacks, and SVG elements dragging
Here is the code.
// simple drag
function sdrag(onDrag, onStop) {
var startX = 0;
var startY = 0;
var el = this;
var dragging = false;
function move(e) {
el.style.left = (e.pageX - startX ) + 'px';
el.style.top = (e.pageY - startY ) + 'px';
onDrag && onDrag(el, e.pageX, startX, e.pageY, startY);
}
function startDragging(e) {
if (e.currentTarget instanceof HTMLElement || e.currentTarget instanceof SVGElement) {
dragging = true;
var left = el.style.left ? parseInt(el.style.left) : 0;
var top = el.style.top ? parseInt(el.style.top) : 0;
startX = e.pageX - left;
startY = e.pageY - top;
window.addEventListener('mousemove', move);
}
else {
throw new Error("Your target must be an html element");
}
}
this.addEventListener('mousedown', startDragging);
window.addEventListener('mouseup', function (e) {
if (true === dragging) {
dragging = false;
window.removeEventListener('mousemove', move);
onStop && onStop(el, e.pageX, startX, e.pageY, startY);
}
});
}
Element.prototype.sdrag = sdrag;
and to use it:
document.getElementById('my_target').sdrag();
You can also use onDrag and onStop callbacks:
document.getElementById('my_target').sdrag(onDrag, onStop);
Check my repo here for more details:
https://github.com/lingtalfi/simpledrag
this is how I do it
var MOVE = {
startX: undefined,
startY: undefined,
item: null
};
function contentDiv(color, width, height) {
var result = document.createElement('div');
result.style.width = width + 'px';
result.style.height = height + 'px';
result.style.backgroundColor = color;
return result;
}
function movable(content) {
var outer = document.createElement('div');
var inner = document.createElement('div');
outer.style.position = 'relative';
inner.style.position = 'relative';
inner.style.cursor = 'move';
inner.style.zIndex = 1000;
outer.appendChild(inner);
inner.appendChild(content);
inner.addEventListener('mousedown', function(evt) {
MOVE.item = this;
MOVE.startX = evt.pageX;
MOVE.startY = evt.pageY;
})
return outer;
}
function bodyOnload() {
document.getElementById('td1').appendChild(movable(contentDiv('blue', 100, 100)));
document.getElementById('td2').appendChild(movable(contentDiv('red', 100, 100)));
document.addEventListener('mousemove', function(evt) {
if (!MOVE.item) return;
if (evt.which!==1){ return; }
var dx = evt.pageX - MOVE.startX;
var dy = evt.pageY - MOVE.startY;
MOVE.item.parentElement.style.left = dx + 'px';
MOVE.item.parentElement.style.top = dy + 'px';
});
document.addEventListener('mouseup', function(evt) {
if (!MOVE.item) return;
var dx = evt.pageX - MOVE.startX;
var dy = evt.pageY - MOVE.startY;
var sty = MOVE.item.style;
sty.left = (parseFloat(sty.left) || 0) + dx + 'px';
sty.top = (parseFloat(sty.top) || 0) + dy + 'px';
MOVE.item.parentElement.style.left = '';
MOVE.item.parentElement.style.top = '';
MOVE.item = null;
MOVE.startX = undefined;
MOVE.startY = undefined;
});
}
bodyOnload();
table {
user-select: none
}
<table>
<tr>
<td id='td1'></td>
<td id='td2'></td>
</tr>
</table>
While dragging, the left and right of the style of the parentElement of the dragged element are continuously updated. Then, on mouseup (='drop'), "the changes are committed", so to speak; we add the (horizontal and vertical) position changes (i.e., left and top) of the parent to the position of the element itself, and we clear left/top of the parent again. This way, we only need JavaScript variables for pageX, pageY (mouse position at drag start), while concerning the element position at drag start, we don't need JavaScript variables for that (just keeping that information in the DOM).
If you're dealing with SVG elements, you can use the same parent/child/commit technique. Just use two nested g, and use transform=translate(dx,dy) instead of style.left=dx, style.top=dy

How to prevent draggable handles in range slider form overlapping?

I have to prevent dragable handles in range slider form overlapping . It is vanilla js plugin.
I tried to disable updating offset if the difference between two handles position is lower than 20px. It works sometimes, but the barrier is not precise. The movement is choppy when the handles are near to each other.The handle cannot be dragged immediately, but after few movements.
Here are the fragments of the plugin code:
// HELPERS
// map slider range to value range
Number.prototype.map = function(in_min, in_max, out_min, out_max) {
return (this - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
// round to nearest multiple
Number.prototype.roundTo = function(num) {
var resto = this % num;
if (resto <= (num / 2)) {
return this - resto;
} else {
return this + num - resto;
}
}
//EVENTS
var EVmove = ('ontouchstart' in document.documentElement) ? 'touchmove' : 'mousemove',
EVmove = ('ontouchstart' in document.documentElement) ? 'touchmove' : 'mousemove',
EVend = ('ontouchstart' in document.documentElement) ? 'touchend' : 'mouseup';
document.addEventListener(EVmove, actions.move, false);
document.addEventListener(EVend, function() {
return movebar = false;
}, false);
document.addEventListener(EVstart, function() {
return movebar = true;
}, false);
var movebar = true;
// MOVE HANDLE
actions.move = function(event) {
var clientX = ('ontouchstart' in document.documentElement) ? event.touches[0].clientX : event.clientX;
leftOffset = clientX - posX;
// move handle bar
if (movebar) {
element.style.left = leftOffset + "px";
var v = leftOffset.map(0, elWidth, 0, window.range); // 0
var value = v.roundTo(step);
output.innerHTML = value.toFixed(2);
// prevent handles ovelaping
if (vsOpts.range) {
var diff = Math.abs(parseInt(handle1.offsetLeft) - parseInt(handle2.offsetLeft));
if (diff < 20) {
movebar = false;
}
}
}
}
I solved it by assigning position of the opposite handle as a limit position of the current handle
document.addEventListener(EVstart, function(event) {
if (event.target.id == "vslider-handle1") {
useHandle1 = true
} else {
useHandle1 = false
}
return movebar = true;
}, false);
}
handle1Limit=parseInt(handle2.offsetLeft);
handle2Limit=parseInt(handle1.offsetLeft);
handle1Pos= parseInt(handle1.offsetLeft);
handle2Pos= parseInt(handle2.offsetLeft);
if(useHandle1){
if(handle1Pos>=handle1Limit){
handle1.style.left = handle1Limit + "px";
handle2.style.left = handle1Limit + "px";
}
}
else{
if(handle2Pos<=handle2Limit){
handle2.style.left = handle2Limit + "px";
handle1.style.left = handle2Limit + "px";
}
}

JavaScript Magnifying glass

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 :)

How to prevent image slider from scrolling too much?

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);
});

Stop function when pressing ctrl jQuery

So I am making a little game where you have to press Ctrl to stop a div from jumping randomly.
However I can't get it working...
The jumpRandom function works fine, until i put the randomJump(){return false;}; inside the if (event.ctrlKey) {}. What should I do to get it working?
js:
$(document).ready(function() {
function randomFromTo(from, to){
return Math.floor(Math.random() * (to - from + 1) + from);
}
$( "#goal" ).bind('mouseenter keypress', function(event) {
if (event.ctrlKey) {
randomJump(){return false;};
}
});
$('#goal').mouseenter(randomJump);
function randomJump(){
/* get Window position and size
* -- access method : cPos.top and cPos.left*/
var cPos = $('#pageWrap').offset();
var cHeight = $(window).height() - $('header').height() - $('footer').height();
var cWidth = $(window).width();
// get box padding (assume all padding have same value)
var pad = parseInt($('#goal').css('padding-top').replace('px', ''));
// get movable box size
var bHeight = $('#goal').height();
var bWidth = $('#goal').width();
// set maximum position
maxY = cPos.top + cHeight - bHeight - pad;
maxX = cPos.left + cWidth - bWidth - pad;
// set minimum position
minY = cPos.top + pad;
minX = cPos.left + pad;
// set new position
newY = randomFromTo(minY, maxY);
newX = randomFromTo(minX, maxX);
$('#goal').fadeOut(50, function(){
$('#goal').fadeIn(700);
});
$('#goal').animate({
left: newX,
top: newY,
duration: 500
});
}
});
Try this:
$("#goal").bind('mouseenter keypress', function (e) {
randomJump(e);
});
function randomJump(e) {
if (!e.ctrlKey) {
//do normal stuff
} else {
//depending on how permanent you need this to be...
//$("#goal").unbind('mouseenter keypress');
}
return !e.ctrlKey;
}

Categories