determining mouse position on a window focus event - javascript

I've attached a focus listener to window (using prototype syntax):
Event.observe( window, 'focus', focusCb.bindAsEventListener( this ) );
I want to determine the mouse position when the window is focused. Unfortunately, in my focusCb method, I don't seem to have access to pageX, pageY, clientX or clientY.
Using quirksmode code:
function doSomething(e) {
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop
+ document.documentElement.scrollTop;
}
// posx and posy contain the mouse position relative to the document
// Do something with this information
}
I always get 0, 0.
I thought the focus event would have the mouse position information.
Why doesn't the focus event have this information?
More importantly, how should get I get the mouse position when the window is focused?

IE has clientX and clientY in the event object; though it may be the only one.
Yeah, this is looking pretty horrible. See the section on this page about Mouse Position. I think he does a pretty thorough job of examining it.
Okay, I see you're actually already using his script. Sigh.

Depending on the circumstances, it might not exactly be what you're looking for, but you could, after the focus, wait for the next mousemove event and use that coordinates, something along this line:
var x = 0, y = 0, window_got_focus = false;
window.onfocus = function () { window_got_focus = true };
document.onmousemove = function (event) {
if (window_got_focus) {
window_got_focus = false;
x = event.clientX;
y = event.clentY;
}
};
Drawback is, of course, that you get the coordinates only as soon as the user moves the mouse after focussing.

You can capture the window onclick event and throw the position into a globally scoped variable.
EDIT: Also if you're using prototype you should have access to the pointerX and pointerY methods of the event object.

call doSomething() function on mouse move
document.onmousemove = function (e)
{
doSomething(e);
};

Related

Raphael: How to unbind the mousemove function on mouseup?

I am drawing a line with Raphael. I have a mousedown event where I store the starting position. While the mouse is down, if the user moves it, I have a mousemove event where I keep drawing the line as the mouse moves.
Now when the mouse button is released, the line should stop. This does not happen and line keeps going on if the mouse moves even though button is released. This line must stop on mouseup. If the user does mousedown again, it should begin a new line.
I have tried many combinations with the unmouse* events, but I am missing something here.
JSFiddle at: http://jsfiddle.net/zaphod013/P33FA/5/
(This is my first date with JS/Raphael. So if you think I am totally off track here, please tell me so)
var g_masterPaper;
var g_startX;
var g_startY;
var g_line;
function initDrawing() {
g_masterPaper = Raphael(10,10,700,500);
var masterBackground = g_masterPaper.rect(10,10,600,400);
masterBackground.attr("fill", "#eee");
var drawit = function(event) {
x = event.pageX - 10;
y = event.pageY - 10;
var linepath = ("M"+g_startX+" "+g_startY+" L"+x+" "+y);
g_line.attr("path", linepath);
};
var startit = function (event) {
g_startX = event.pageX - 10;
g_startY = event.pageY - 10;
g_line = g_masterPaper.path("M"+g_startX+" "+g_startY+" L"+g_startX+" "+g_startY);
masterBackground.mousemove(drawit);
};
masterBackground.mousedown(startit);
masterBackground.mouseup(function (event) {
this.unmousedown(startit);
this.unmousemove(drawit);
});
return g_masterPaper;
}
window.onload = function () {
var paper=initDrawing();
paper.text(15,475,'Use your mouse to draw.').attr({fill:'#ff0000', 'font-size':24, 'stroke-width':1,'text-anchor':'start' });
}
I think you're on track and mostly looks fine, I would possibly just simplify your handlers, and not keep removing/adding them, it keeps handlers hard to track and debug. So I would just have one handler for down/up/move...
Edit:
jsfiddle here or here which gets around other elements capturing the mouseup event and stopping it working properly.
var drawit = function(event) {
event.preventDefault();
x = event.pageX - 10;
y = event.pageY - 10;
var linepath = ("M"+g_startX+" "+g_startY+" L"+x+" "+y);
if( g_line ) { g_line.attr("path", linepath) };
};
var startit = function (event) {
event.preventDefault();
g_startX = event.pageX - 10;
g_startY = event.pageY - 10;
g_line = g_masterPaper.path("M"+g_startX+" "+g_startY+" L"+g_startX+" "+g_startY);
};
var finish = function ( event ) {
g_line = '';
}

onbeforemousemove to get mouse's old position?

I'm working on a drag and drop lib and i would like to add the mouse's position variation to the dragged element's actual position instead of just setting it's position to the current cursor position in the window. This would allow me not to use position: fixed and be able to drag position relative/absolute; elements.
To know the old position of the mouse (before the mousemove handler is called) i can just store the position in a variable in the previous call to that handler using e.pageX and pageY. But what about the first time the mouse handler is moved ? How can i know the old mouse position to determine it's variation when i havn't stored that old position yet ?
A piece of code :
var $dragged = null,
$window = $(window),
oldMouseX = null,
oldMouseY = null;
var mouseMoveHandler = function(e) {
var curTop = $dragged.css('top'),
curLeft = $dragged.css('left');
$dragged.css({
top : curTop + e.pageY - oldMouseY,
left : curLeft + e.pageX - oldMouseX,
});
oldMouseX = e.pageX;
oldMouseY = e.pageY;
};
$('.Draggable')
.attr('draggable', true)
.css({userSelect: 'none'})
.on('mousedown', function() {
$dragged = $(this);
$window.bind('mousemove', mouseMoveHandler);
})
.on('mouseup', function() {
$dragged = null;
$window.unbind('mousemove', mouseMoveHandler);
})

JavaScript cannot get onmousemove script to work as intended

I have a function to follow the object after the mouse,
and I want to be able to stop and start following at will, without hiding the object.
It almost works as I wanted, and is following the mouse indeed, but I cannot make it move initial position without actually moving the mouse.
E.G. When I trigger the function, the object is still somewhere in another place, until I move the mouse, but what I'm trying to do is to move it the initial position first, before attaching the mousemove event.
Here is how I want to trigger the function:
showtrail();
function showtrail(shit){
//this is how I tried to set the initial position first, but this get me an error:..
//followmouse();
document.onmousemove=followmouse; //and this is how I attach the event.
}
This is a part of the actual function to move the object,
but, I can't get the coordinates if I try to initilize/imitate the first movement.
function followmouse(e){
var xcoord=offsetfrommouse[0]
var ycoord=offsetfrommouse[1]
if (typeof e != "undefined"){ //This- if triggered by mousemove, and it works
xcoord+=e.pageX
ycoord+=e.pageY
}
else { //this was meant for the initial call, but... for some reason
xcoord+=document.body.scrollLeft+event.clientX // it triggers an error,
ycoord+=document.body.scrollTop+event.clientY // saying event.clientX undefined.
}
}
So the event.clientX never seems to work, and I cannot figure out how to get the actual mouse position otherwise..
Please guide..
event.clientX and event.clientY are wrong. They should be e.clientX and e.clientY
A more elegant cross browser way to get xcoord and ycoord in followmouse(e) is:
xcoord = e.pageX||(e.clientX+(document.body.scrollLeft||document.documentElement.scrollLeft));
ycoord = e.pageY||(e.clientY+(document.body.scrollTop||document.documentElement.scrollTop));
Now if I'm getting it right, the object that follows is expected to have an initial absolute position and displayed as a block, meaning that you have initial x and y (left and top). Therefore by using a global bool var for currently following or not you're done.
<style>
...
#trail {position:absolute;left:0;top:0;display:none}
...
</style>
<script>
var following = false;
...
function followmouse(e){
if (!following){
document.getElementById('trail').style.display='none';
return;
}
...
document.getElementById('trail').style.display='block';
}
</script>
By changing display you have the option to move your #trail to its initial position and then follow the mouse, and the option to avoid the move and let it follow the mouse from its latest following position.
EDIT 1:
For this very purpose, I recommend using of requestAnimationFrame API, not classic DOM events. said API is more efficient for creating animations and pausing them.
take a look at this too: requestAnimationFrame for smart animating
This is sad, but true that you can not get mouse's initial position before moving mouse on a webpage. I mean you can't calibrate your object before mousemove event. this is what I will do in a similar project:
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<script type="text/javascript">
var targetID = 'mydiv'; // div that is to follow the mouse
var pauseFollowing = false;
// (must be position:absolute)
var offX = 15; // X offset from mouse position
var offY = 15; // Y offset from mouse position
function mouseX(evt) {if (!evt) evt = window.event; if (evt.pageX) return evt.pageX; else if (evt.clientX)return evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft); else return 0;}
function mouseY(evt) {if (!evt) evt = window.event; if (evt.pageY) return evt.pageY; else if (evt.clientY)return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); else return 0;}
function follow(evt) {
if(pauseFollowing) {
//or do something else at pause
return false;
}
var obj = document.getElementById(targetID).style;
obj.visibility = 'visible';
obj.left = (parseInt(mouseX(evt))+offX) + 'px';
obj.top = (parseInt(mouseY(evt))+offY) + 'px';
}
function toggleFollow() {
pauseFollowing = !pauseFollowing;
}
window.onload = function() {
window.onclick = toggleFollow;
document.onmousemove = follow;
}
</script>
</head>
<body>
<div id="mydiv" style="visibility: hidden; top:0; left:0 ;width: 100px; height: 100px; background: #ff0; position: absolute;"></div>
</body>
</html>
Alright that's how I done it.
The best Idea was to always capture a move to set position in a global var.
Now I have an option to display it fixed at any specific place (if I pass coords to showtrail)
or to actually follow the mouse;
I also added an event listener, so if the mouse gets outside the window while following- it will be hidden.
So far it works exactly as I wanted:
var trailimage=["scripts/loading_mouse.gif", 24, 24] //image path, plus width and height
var offsetfrommouse=[2,10] //image x,y offsets from cursor position in pixels. Enter 0,0 for no offset
var global_coord=[0,0]
var follow=false;
if (document.getElementById || document.all)
document.write('<div id="trailimageid" style="z-index: 10;position:absolute;display:none;left:0px;top:0px;width:1px;height:1px"><img src="'+trailimage[0]+'" border="0" width="'+trailimage[1]+'px" height="'+trailimage[2]+'px"></div>')
function gettrailobj(){
if (document.getElementById)
return document.getElementById("trailimageid").style
else if (document.all)
return document.all.trailimagid.style
}
function hidett(){ gettrailobj().display="none"; }
function showtt(){ gettrailobj().display="block"; }
function truebody(){ return (document.body||document.documentElement); }
function showtrail(shit){
if (typeof shit == "undefined"){ //Follow Mouse
follow=true;
setmousepos(global_coord[0],global_coord[1]);
}
else { //Set fixed in specific place
follow=false;
showtt()
gettrailobj().left=shit.left+6+"px"
gettrailobj().top=shit.top-5+"px"
}
}
function hidetrail(){
hidett()
follow=false;
}
function setcoord(e){
var xcoord=offsetfrommouse[0]
var ycoord=offsetfrommouse[1]
var xxcoord = e.pageX||(e.clientX+truebody().scrollLeft);
var yycoord = e.pageY||(e.clientY+truebody().scrollTop);
if (typeof xxcoord != "undefined"&&typeof yycoord != "undefined"){
xcoord+=xxcoord;
ycoord+=yycoord;
global_coord=[xcoord,ycoord];
if (follow) setmousepos(xcoord,ycoord);
}}
function setmousepos(xcoord,ycoord){
var docwidth=truebody().scrollLeft+truebody().clientWidth
var docheight=Math.max(truebody().scrollHeight, truebody().clientHeight)
if ((xcoord+trailimage[1]+3>docwidth || ycoord+trailimage[2]> docheight ||!follow)){
hidett()
}
else{
showtt();
gettrailobj().left=xcoord+"px"
gettrailobj().top=ycoord+"px"
}
}
window.addEventListener("mouseout",
function(e){
mouseX = e.pageX;
mouseY = e.pageY;
if ((mouseY >= 0 && mouseY <= window.innerHeight)
&& (mouseX >= 0 && mouseX <= window.innerWidth)){
return false;
}else{
if (follow) hidett()
}
},
false);
document.onmousemove=setcoord;

Getting mouse position in keyboard event

I'm trying to have a selection wheel appear when the user holds down the Shift key.
The wheel should be centred on the mouse's position.
However when I test this, pageX and clientX are both undefined on the event object.
Is it possible to get the mouse coordinates on a keyboard event?
No, simply track mousemove events and continuously save the current position in case you get a keyboard event.
Cache mouse position in a global variable in every mousemove event and use it when a key event fires:
var mousePosition = {x:0, y:0};
$(document).bind('mousemove',function(mouseMoveEvent){
mousePosition.x = mouseMoveEvent.pageX;
mousePosition.y = mouseMoveEvent.pageY;
});
$(document).bind('keyup', function(keyUpEvent){
$('body').append($('<p/>').text('x:' + mousePosition.x + ' * y: ' + mousePosition.y));
});
JSBIN: http://jsbin.com/uxecuj/4
JavaScript without jQuery:
var mousePosition = {x:0, y:0};
document.addEventListener('mousemove', function(mouseMoveEvent){
mousePosition.x = mouseMoveEvent.pageX;
mousePosition.y = mouseMoveEvent.pageY;
}, false);
document.addEventListener('keyup', function(keyUpEvent){
var divLog = document.querySelector('#log'),
log = 'x:' + mousePosition.x + ' * y: ' + mousePosition.y,
p = document.createElement('p').innerHTM = log;
divLog.appendChild(p);
}, false);
Here's the POJS equivalent of other answers that is cross browser back to IE 6 (and probably IE 5 but I don't have it to test any more). No global variables even:
function addEvent(el, evt, fn) {
if (el.addEventListener) {
el.addEventListener(evt, fn, false);
} else if (el.attachEvent) {
el.attachEvent('on' + evt, fn);
}
}
(function () {
var x, y;
window.onload = function() {
addEvent(document.body, 'mousemove', function(e) {
// Support IE event model
e = e || window.event;
x = e.pageX || e.clientX;
y = e.pageY || e.clientY;
});
// Show coords, assume element with id "d0" exists
addEvent(document.body, 'keypress', function() {
document.getElementById('d0').innerHTML = x + ',' + y;
});
}
}());
But there are bigger issues. Key events are only dispatched if an element that can receive keyboard input is focused (input, textarea, and so on). Also, if the user scrolls the screen without moving the mouse, the coordinates will probably be wrong.
An alternative solution is to use CSS to replace the cursor with a custom animation.
If you're using jQuery, you can do the following (assuming you have an image with id="wheelImage" and whose position is set to absolute), write the following inside your keydown event. Here we use the global properties pageX and pageY that are passed to any handler. You can also use jQuery's shiftKey property to check if the shift key has been pressed.
$().keydown(function(e) {
if (e.shiftKey) {
e.preventDefault();
$('#wheelImage').css('left',e.pageX ).css('top', e.pageY);
}
});
Cache the mouse position.
var x = 0, y = 0;
document.addEventListener('mousemove', function(e){
x = e.pageX
y = e.pageY;
}, false);
document.addEventListener('keyup', function(e){
console.log(x + ' ' + y);
}, false);
Or with JS Ninja Library.
var x = 0, y = 0;
$(document).mousemove(function(e){
x = e.pageX
y = e.pageY;
});
$(document).keypressed(function() {
console.log(x + ' ' + y);
});

JavaScript how to check drag direction

I am trying to monitor dragStart and dragEvent javascript, in order to conclude its direction, UP or DOWN.
However i could not get any detail in arguments passed by the event -- that help to conclude.
Is there any better way to check drag direction , up or down?
Note:
my problem is specifically happening at mojo javascript at webos
Thanks,
-iwan
I didn't know about dragStart and dragEvent, but why not use onmousedown, onmousemove and onmouseup?
I made a modified version of http://dunnbypaul.net/js_mouse/. The direction is displayed in #status when you drag the image. Tested and works in IE5.5, IE6, IE7, IE8, Safari 5, Chrome 6 and Navigator 9. Works with Strict Doctype (probably other Doctypes also, didn't test them).
JavaScript:
var dragobj = null;
function getCurY(e) {
if (!e) e = window.event;
if (e.pageX || e.pageY)
return e.pageY;
else if (e.clientX || e.clientY)
return e.clientY + document.body.scrollTop;
}
function drag(context, e) {
dragobj = context;
document.onmousedown = function() { return false };
document.onmouseup = function() {
if (dragobj) dragobj = null;
document.getElementById('status').innerHTML = 'Direction: n/a';
}
var graby = getCurY(e);
var oriy = dragobj.offsetTop;
document.onmousemove = function(e) {
if (dragobj) {
dragobj.style.position = 'absolute';
var newy = oriy + getCurY(e) - graby;
var dir = newy > parseInt(dragobj.style.top, 10) ? 'down' : 'up';
dragobj.style.top = newy + 'px';
document.getElementById('status').innerHTML = 'Direction: ' + dir;
}
return false;
}
}
HTML:
<p onmousedown="drag(this, event)">
<img src="http://1.bp.blogspot.com/-u3FKHnFg8cA/Td56DmfliyI/AAAAAAAAAJ8/fTCFNCTs7iE/s1600/trollface%255B1%255D.jpg" alt="Trollface" />
</p>
<p id="status" style="position:absolute; top:0">Direction: n/a</p>
It won't tell you the direction, but you can get the position of the element you're dragging and figure out which direction it's going.
This might be helpful: http://dunnbypaul.net/js_mouse/.
You want to use dragOver. You could do something like this if you're only interested in vertical position:
Javascript:
<script type="text/javascript">
function getPosY(event) {
console.log(event.clientY);
}
</script>
HTML:
<body ondragover="getPosY(event)">
EDIT: Here's a jsfiddle. Make sure your js console is open.
You could have your function compare the clientY values to determine which direction the mouse is moving.

Categories