Can you please take a look at this demo and let me know how I can detect whether the mousemove is toward Left or Right?
$('.container').mousedown(function(){
$(this).mousemove(function(){
//if Moves Left { console.log("Moving Left"); }
//if Moves Right { console.log("Moving Right"); }
});
});
$('.container').mouseup(function(){
$(this).unbind("mousemove");
});
.container {
height:200px;
width:200px;
background-color:#1abc9c;
}
<script src=".1.1/jquery.min.js"></script>
<div class="container"></div>
Can you please take a look at this demo and let me know how I can detect whether the mousemove is toward Left or Right?
$('.container').mousedown(function(){
$(this).mousemove(function(){
//if Moves Left { console.log("Moving Left"); }
//if Moves Right { console.log("Moving Right"); }
});
});
$('.container').mouseup(function(){
$(this).unbind("mousemove");
});
.container {
height:200px;
width:200px;
background-color:#1abc9c;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>
Share
Improve this question
asked Oct 3, 2015 at 7:11
SuffiiSuffii
5,78415 gold badges62 silver badges94 bronze badges
3 Answers
Reset to default 4Definitely one off the many solution:
$('.container').mousedown(function(e1){
var mx = e1.pageX;//register the mouse down position
$(this).mousemove(function(e2){
if (e2.pageX > mx){ //right w.r.t mouse down position
console.log("Moved Right");
} else {
console.log("Moved Left")
}
});
});
$('.container').mouseup(function(){
$(this).unbind("mousemove");
});
working code here
Hay this is quite easy just add this code inside you script tag and view on your console.
var bodyElement = document.querySelector("body");
bodyElement.addEventListener("mousemove", getMouseDirection, false);
var xDirection = "";
var yDirection = "";
var oldX = 0;
var oldY = 0;
function getMouseDirection(e) {
//deal with the horizontal case
if (oldX < e.pageX) {
xDirection = "right";
} else {
xDirection = "left";
}
//deal with the vertical case
if (oldY < e.pageY) {
yDirection = "down";
} else {
yDirection = "up";
}
oldX = e.pageX;
oldY = e.pageY;
console.log(xDirection + " " + yDirection);
}
$('.container').mousedown(function(e){
var prevX = e.clientX;
$(this).mousemove(function(e){
if(e.clientX < prevX) { console.log("Moving Left"); }
if(e.clientX > prevX) { console.log("Moving Right"); }
prevX = e.clientX;
});
});
$('.container').mouseup(function(){
$(this).unbind("mousemove");
});
.container {
height:200px;
width:200px;
background-color:#1abc9c;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>