I wanted to find out the co-ordinates of the mouse click event on the page. Wrote a little piece of JS which works well on Chrome but not on Firefox. Seems the default global 'event' is not available in Firefox. Here is a smaller version of the code that worked on Chrome:
$("body").click(function() {
if (event == undefined) // for Chrome, 'event' is not undefined here
var event = window.event;
var xx;
var yy;
if (event) {
// Need this for Chrome (and IE)
xx = event.x;
yy = event.y;
} else {
// firefox
// WHAT SHOULD I DO HERE?
}
console.log('Click called on body.' + xx + ':' + yy);
}
What should I manage the Firefox case?
jQuery (which it looks like you are using) sorts out the event parameter versus global event property issue for you, so you don't need to worry about that. It also normalizes pageX and pageY properties.
$("body").click(function(evt) {
var xx = evt.pageX;
var yy = evt.pageY;
console.log('Click called on body.' + xx + ':' + yy);
});
JQuery passes the event as the first argument to your click handler.
You've forgotten to pass the event as a parameter. Use the below format, and do a console.log(e) to get all the data associated with it. But I'm not sure it has x and y coordinates, you might have to get the coordinates of the element it clicked.
$("body").click(function(e) {
}
EDIT: pageX and pageY seem to be provided, along with a bunch of others...
You need to pass the event variable in the click function call e.g.
.click(function(e){
console.log(e);
});
Related
I want to set an elements position equal to the position of the cursor every one second. But as soon as i include the setTimout attribute in the function it stops working and prints the following error in the log: "Uncaught RangeError: Maximum call stack size exceeded".
I have tried to run the code without a timeout but then the page freeze.
Here is the code that i can't get to work:
function moveElement() {
while (true) {
x = event.clientX;
y = event.clientY;
document.getElementById("status").innerHTML = x + " " + y; //This line is not important
setTimeout(moveElement(), 1000);
document.getElementById("test").style.color = "blue";
document.getElementById("test").style.left = x + "px";
document.getElementById("test").style.top = y + "px";
}
};
Also i get this error when i try to run event.clientX outside a function: "Uncaught TypeError: Cannot read property 'clientX' of undefined"
Can somebody see what is wrong with my code or just tell me another method to get it to work (no jQuery please)? Thank you.
/HamMan4Ever
This example waits until the mouse has stopped moving and then waits a second, then applies the new position.
I can create another example that just updates the position every second although it might be a good idea to wait for the mouse to stop moving.
This code waits for a mousemove and then clears any existing timers that are running and then sets up a new one. It also captures and stores the information about the mouse move to be used later.
Since the mousemove event is a recurring event (it fires like a thousand times whenever you move the mouse) which is why whenever the mouse is moved, all timers are cleared to avoid having multiple timers set at the same time.
The end result of this code is that when you move the mouse, it will wait until you have stopped moving the mouse, waits one second, and then sets the divs coord.
Please let me know in the comments if there is anything else I can do for you.
window.addEventListener('load',function(){//when the page loads
//initialize all variables.
var timer = false;
var updateTracking = false;
var x = 0;
var y = 0;
window.addEventListener('mousemove',function(e){//when the mouse is moved.
clearTimer();//clear the existing timer
updateTracking = true;//set the flag so that the if statement knows the mouse has been moved.
x = e.x;//get the X coord of the mouse move
y = e.y;//get the Y coord of the mouse move
setTimer();//set a timer for 1 second.
});
//the function that sets the timer.
function setTimer(){
//set the "timer" variable to a timer function
timer = window.setTimeout(function(){
if(updateTracking == true){//if the mouse has been moved
var elem = document.getElementById('theDiv');//get the element
updateTracking = false;//reset the flag since the element has been updated
elem.style.top = y+'px';//set the Y coord of the element
elem.style.left = x+'px';//set the X coord of the element
}
},1000);
}
function clearTimer(){//cleat timer function; clears any existing timers
window.clearTimeout(timer);//clear the timer
}
});
#theDiv{
width:30px;
height:30px;
background:red;
position:absolute;
}
<div id="theDiv"></div>
Here is another code snippet that shows you how the mousemove event functions. Just open your console and move the mouse...
window.onload = function(){
window.onmousemove = function(){
console.log('the mouse was moved');
};
};
The first parameter to setTimeout must be a function. When you use code like moveElement() you are calling the function (again) instead of just providing a reference to it. So I think you would be better of doing something like this:
setTimeout(moveElement, 1000);
The while (true) loop is causing your page to freeze because it is an eternal loop; It will run your code repeatedly, forever and doesn't give your browser time to breathe. The poor thing.
You have this line:
setTimeout(moveElement(), 1000);
Which should be:
setTimeout(moveElement, 1000);
Parentheses at the end of a function calls it immediately. So this function was just calling itself over and over. You want to pass a reference to the function that timeout should call after the specified time.
Uncaught RangeError: Maximum call stack size exceeded
You also should remove while(true) which will just loop forever. This is most likely why you received the above error. If you want to call this function every second just use setTimeout which will wait the amount of time specified and then call the function reference you passed it.
Uncaught TypeError: Cannot read property 'clientX' of undefined
This happens because there is no event variable that exists. Usually an event is passed to a function that has been attached as a handler to some event.
Here is an example of attaching an event and using clientX/clientY in some way. Perhaps it will help you understand and expand on it to do whatever it is you are trying to do:
Fiddle: http://jsfiddle.net/tqpvkjd9/
HTML:
<div id="test">some text</div>
JS:
function moveElement (event) {
var x = event.clientX;
var y = event.clientY;
var test = document.getElementById("test");
test.style.color = "blue";
test.style.left = x + "px";
test.style.top = y + "px";
};
document.addEventListener('mousemove', moveElement);
CSS:
div {
height: 100px;
width: 100px;
background: red;
position: absolute;
top: 0;
left: 0;
}
And lastly you should really declare x and y using var as I did above. Without var they are assumed to be global variables which is usually not good.
So I want to be able to trigger my mousemove function in jquery using $().mousemove(), but I want to also be able to pass the current mouse state as a parameter, so my mousemove function knows the mouse x and y coordinates.
I understand that a possible workaround is just to save the x and y coordinates and create a function that directly uses these coordinates, but I wanted to know if there was a way to just get the current mouse event.
Example:
$(document).mousemove(function(e) {
var x = e.pageX;
var y = e.pageY;
// do stuff with x and y
});
function trigger_mousemove() {
$(document).mousemove(/** here is where I want something to be able to put in */);
}
Thanks in advance!
Use a closure to give your whole code access to a variable that is updated by a mousemove handler:
var mouseX, mouseY;
$(document).mousemove(function(e) {
mouseX = e.pageX;
mouseY = e.pageY;
}).mouseover(); // call the handler immediately
// do something with mouseX and mouseY
cytation from user lonesomeday if you like the answer give him credit in link below.
See How to get mouse position in jQuery without mouse-events? for reference
I'm doing my first project in kineticJS; I have to drag some shapes on the canvas and in the meanwhile, I have to write somewhere on the page the coordinates of the shape in real time. In order to do this I use the event "dragmove" on the layer like this:
layer.on("dragmove",function(evt) {//detect shape and write stuff});
I used "targetNode" for catching the clicked shape.
The problem is this: if I use targetNode on a shape that is not part of any group, everything works, but if the node that has to be moved is part of a group, targetNode only works the first time and then return an undefined value for all times following (dragmove usually takes some time, not like dragstart or click).
I made a fiddle so you can see what I'm talking about:
http://jsfiddle.net/UScmU/
The 2 rects are in a group. if you click on a shape, an alert return its name, if you drag the circle or the rects, on the console will be written the shape's name.
I would appreciate some help. sorry for my english, I also hope the text is understandable.
For some reason evt.targetNode is only defined the first call on dragmove then it turns undefined, you can see this by doing this:
layer.on("dragmove",function(evt) {
console.log(evt.targetNode);
console.log(evt.targetNode.getName()+"");
});
Instead, try using defining var nodo outside of the event functions, and then set nodo = evt.targetNode on mousedown.
var nodo;
layer.on('mousedown', function(evt) {
nodo = evt.targetNode;
});
layer.on("click", function (evt) {
console.log(nodo.getName() + "");
});
layer.on("dragmove", function (evt) {
console.log(nodo.getName() + "");
});
JSFIDDLE
It's OS/user dependant. Not the browser, not the website, but the OS decides how fast and slow a double click must be.
I'd like to use that number in my app. Is there a way to get that number with JS?
Simple question. Might not be possible.
Thanks
Simple answer: no, sorry.
The best you could do would be something like this (example uses jQuery simply because it was quicker to write, the principle holds if jQuery is unavailable. Also note that this could well be simplified, this is just what came to mind first):
var timer,
num = 0;
$("#example").click(function() {
/*This condition is required because 2 click events are fired for each
dblclick but we only want to record the time of the first click*/
if(num % 2 === 0) {
timer = (new Date()).getTime();
}
num++;
}).dblclick(function() {
var time2 = (new Date()).getTime(),
dblClickTime = time2 - timer;
});
Unfortunately, that's probably not very helpful. You may be able to record the dblClickTime values and check for the longest, but that still is very unlikely to be the actual value you're after. That sort of thing is just not available through JavaScript.
Answer 2021 - as far as I know - still not. There is a reason: we should not care.
In principle dblclick is somehow obsolete …
We have the not well known detail property. Maybe because of the name.
From MDN:
The MouseEvent object passed into the event handler for click has its detail property set to the number of times the target was clicked. In other words, detail will be 2 for a double-click, 3 for triple-click, and so forth. This counter resets after a short interval without any clicks occurring; the specifics of how long that interval is may vary from browser to browser and across platforms. The interval is also likely to be affected by user preferences; for example, accessibility options may extend this interval to make it easier to perform multiple clicks with adaptive interfaces.
With detail ie. click_count it is possible to stop propagation of CLICK when detail != 1
So pseudcode:
if evt.detail==1
do_click()
if evt.detail==2
do_dblclick()
...
if evt.detail!=1
evt.stopPropagation()
If someone really needs to distinguish between click, double-click, triple-click, … like an 'XOR', they should really rethink the design.
The DblClickTime can be very long, that means the app feels like not responding, if the user just wants the click-action.
The other problem is, that it is possible, that users intention is a double-click, but is to slow - then there are two click-actions, they should not be to different to dblclick.
I'd like to use that number in my app. Is there a way to get that number with JS?
Definitely not - stuff like this is outside JavaScript's scope.
You may be able to find out values that work for a double click by asking the user to double-click, listen to the click events and see whether the dblclick event is fired - I'm nnot sure whether event handling works that way, though. But even if that works, it is still a long way from actually finding out the actual value.
This is my 2015 solution, would like to see a pure js version tho.
var start;
var click = null;
$(document).click(function() {
var now = performance.now();
start = click ? click : now;
click = now;
}).dblclick(function() {
alert(performance.now()-start)
});
EDIT
Pure JS
var start;
var click = null;
var getStart = function() {
var now = performance.now();
start = click ? click : now;
click = now;
}
var getStop = function() {
alert(performance.now()-start)
}
if (window.addEventListener) {
window.addEventListener('click', getStart , false);
} else {
window.attachEvent('onclick', function() {
return(getStart.call(window, window.event));
});
}
if (window.addEventListener) {
window.addEventListener('dblclick', getStop , false);
} else {
window.attachEvent('ondblclick', function() {
return(getStop.call(window, window.event));
});
}
Adding on to James Allardice's answer:
Depending on your implementation and where you are looking for double clicks you may want to also check the users mouse location (or I guess tap location). This is to avoid a double click firing when the user is clicking things on different parts of your page (again depends on your event listener implementation -- if it is just on one button for example this probably isn't an issue).
When a click event fires the event listener in my example below has two variables e.clientX and e.clientY. This will give you the location of the mouse. You might want to check to see if the user has moved their mouse significantly since the first click (adapt accordingly to your code).
document.addEventListener("click", function(e){ console.log("Mouse X: " + e.clientX + ": Mouse Y: " + e.clientY); });
You don't want to have it be too tight or else a user may never be able to fire a double click, and you don't want it to be too loose so that double clicks fire seemingly randomly for the user. Maybe start with a 25px or so box around the first click (again this depends on your application). This is something you can test and adjust based on your user interface.
I am assuming you don't have jQuery or aren't using it, because I believe jQuery might already do this calculation to fire dblclick
I'm using firebug and the latest FF to debug this bit of javascript. When line #30 is hit in the debugger the screen tries to refresh with message
"To display this page, firefox must
send information that will repeat any
action (such as a search or order
confirmation) that was performed
earlier.
Javascript with line #'s Called via OnClick()
function EnterComment(divName, /*...couple other params*/) {
25
26 thatDiv = divName;
27 //...comment
28
29 // Mouse Position with offset
30 var x = window.event.screenX + 10;
31 var y = document.body.scrollTop + 20;
This doesn't work in IE either. Is there any way to get an exception from Firebug? Any other tips to fix this?
Firefox doesn't have a global "event" object at all. Instead, a reference to an essentially similar object is passed in to event handlers by the runtime system.
I can't tell what sort of code is that fragment you posted. As an example, if you're binding event handlers with the basic DOM 0 attributes, you can do this:
<a onclick='yourhandler(event)'>hi</a>
and then:
function yourhandler(event) {
event = event || window.event;
var X = event.screenX;
// ...
}
If, as you mention in a comment, you were to use jQuery to bind handlers, then it's even easier because it's the same in all browsers:
$(function() {
$('#myAnchor').click(function(event) {
var X = event.pageX;
});
});