This example implements mousemove event handler using a custom element.
The need was raised few times by designers who wanted to create animations based on mouse move and position.
Here is the live demo and a template to view the code.
2 things to keep in mind when using custom element:
-
The solution can only run on premium sites
-
Code may only run the published site, i.e. in some case it won’t work on preview mode
I’m focusing only on the mousemove code ( highlighted code ) and not on the animation code.
Homepage code
import {setArrowDirection,getArrowPosition} from 'public/arrow-rotate.js';
$w.onReady(function ()
$w('#customElement1').on('coor', (event) => {
$w('#coorText').text="Mouse location: "+event.detail.x+','+event.detail.y;
//Arrow animation
setArrowDirection(event.detail.x,event.detail.y);
});
//Get The arrow element position data from the Custom Element
$w('#customElement1').on('element-data', (event) => {
getArrowPosition(event.detail);
console.log('arrow position retrieved from customelement');
});
})
mouse-move.js (source of the custom element)
const functionsStr=
`document.body.addEventListener("mousemove", myFunction);
function myFunction(e) {
var x = e.clientX;
var y = e.clientY;
var coor = "Coordinates: (" + x + "," + y + ")";
document.getElementsByTagName("mouse-move")[0].dispatchEvent(new CustomEvent('coor',{detail:{x:x,y:y}}));
}`;
class MouseMove extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
var funcScript=document.createElement('script');
funcScript.innerHTML=functionsStr;
this.appendChild(funcScript);
}
static get observedAttributes() {
return ['element-id'];
}
attributeChangedCallback(name, oldValue, newValue) {
const elemenPosition=document.getElementById(newValue).getBoundingClientRect();
this.dispatchEvent(new CustomEvent('element-data',{detail: elemenPosition}));
}
}
customElements.define('mouse-move', MouseMove);
If you check the animation code then you can see a code solution to find the position of the arrow element.
Have fun!