Pointer position example
This example will attach an event listener to the body element of the web page, and listen for mousemove
.
Script.OnInit = function () {
document.body.addEventListener('mousemove', (e) => {
Script.Outputs.PointerX = e.clientX
Script.Outputs.PointerY = e.clientY
})
}
Now lets extend this to also include the mousedown
event, so it updates directly when a pointer event starts, not just when it moves. Since we need the same code twice we can add it to a function.
function setPosition(e) {
Script.Outputs.PointerX = e.clientX
Script.Outputs.PointerY = e.clientY
}
Script.OnInit = function () {
document.body.addEventListener('mousemove', setPosition)
document.body.addEventListener('mousedown', setPosition)
}
We can extend this even further by removing the event listener when the JavaScript node is destroyed. This can happen when a user navigates from a page that runs this code, or when a component with this code is generated by a Repeater node.
function setPosition(e) {
Script.Outputs.PointerX = e.clientX
Script.Outputs.PointerY = e.clientY
}
Script.OnInit = function () {
document.body.addEventListener('mousemove', setPosition)
document.body.addEventListener('mousedown', setPosition)
}
Script.OnDestroy = function () {
document.body.removeEventListener('mousedown', setPosition)
document.body.removeEventListener('mousemove', setPosition)
}