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
Related
var box=document.getElementById("box");
var display=document.getElementById("display");/*to display clientX result*/
var x=box.clientX;
box.addEventListener("click", show);
function show(){
display.innerHTML=x;
}
I feek like there is something simple going over my head that I just cant see
If you want to get the x-position of the mouse-click inside the box-element, you can achieve this with the help of the properties provided by the click-event.
let box = document.getElementById("box");
let display = document.getElementById("display");
function showMouseX(event){
display.innerHTML = event.clientX;
}
box.addEventListener("click", showMouseX);
The properties are clientLeft and clientTop, not clientX and clientY. See the Element interface. So
var x=box.clientLeft;
// -------------^^^^
Separately, and this may or may not be a problem depending on what you're doing, the line
var x=box.clientX;
gets the value of clientX from box as of when it runs, and then stores that value. There's no ongoing connection between x and box.clientX. So when the click occurs later and show is called, it shows the value as of earlier, when var x=box.clientX; ran. Depending on when that is, even if you make it clientLeft, you may get 0 instead of a valid value (if you're reading it during the initial loading of the page, and so the page may not have been laid out yet). Again, depending on what you're doing, you may want to wait and look up box.clientLeft when the click occurs. E.g.:
var box = document.getElementById("box");
var display = document.getElementById("display");
box.addEventListener("click", show);
function show(){
display.innerHTML = box.clientLeft;
}
I have an object with chainable functions, it works ok-ish. Clicking on the triangle itself trigger an animation and translates the element accordingly.
Now I have another function which should translate the triangle to the current mouse position, the js is the following:
moveToTarget: function(e) {
var mouseX = 0,
mouseY = 0,
xp = 0,
yp = 0;
xp += (mouseX - xp) / 12;
yp += (mouseY - yp) / 12;
block.style.left = xp + 'px';
block.style.top = yp + 'px';
setTimeout(moveToTarget,30);
return this;
Keep in mind this is just one of the methods on the object animateBlock and I am not sure if I have to call it as animateBlock.moveToTarget in that SetTimeout.
This is the invocation:
container.addEventListener("click", function(e){
console.log(e.pageY); // this log the Y position
animateBlock.moveToTarget;});
I get no JS lint errors, no runtime errors thrown in console, it just does not apply the translation for some reason, what am I missing here?
The Link:
https://codepen.io/damianocel/pen/MvvXoq
Here's a working codepen: https://codepen.io/anon/pen/mMXwwV?editors=0111
I had to make several changes, so my apologies:
You were calling moveToTarget() without its parameter, the event
The moveToTarget() function wasn't doing anything. You weren't using event, so the values were always 0.
I removed the margin: 50% 0; from the triangle, since it messed with its X position (making using translateX() difficult).
I put the "px" directly inside the function, so the parameters are only numbers now.
New function moveXAndY() so to modify both translateX() and translateY() at the same time (otherwise they'd overwrite each other).
Code's kind of a mess, I'm not used to editing on CodePen, so apologies for that.
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.
I am having some trouble right now with the event.pageX and event.pageY functions. I am trying to use them to grab the location of the mouse on a click event relative to my canvas element. I get the position relative to my canvas with these lines of code:
var mx = e.pageX - this.xPos;
var my = e.pageY - this.yPos;
this.xPos and this.yPos are obtained by using jQuery's offset function:
this.xPos = $("#timelines").offset().left;
this.yPos = $("#timelines").offset().top;
When I log either of these separately (e.pageX/Y or this.x/yPos), they give me the correct numbers. However, when I log the result of mx and my after subtracting, it says that it is not a number (NaN). I have looked around online but haven't found anything that could explain why this is happening. I have tried explicitly casting them using Number(event.pageX/Y) and/or Number(this.x/yPos) but that didn't work. Does anyone have any suggestions?
Try parseFloat() around whatever base vars are non-numeric. That turns '1' (a float) into 1 (numeric)
Not familiar with jQuery, but ensure there is no 'px' at the end of the offset function?
Finally try and trigger one alert (or console.log if you must) with ALL variables that are giving you trouble to find and isolate the problem.
Nvm, i figured out this issue. the value of this was changing in the event listener and not accessing the correct xPos/yPos
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);
});