EventsInteractivity
useMousePosition
A hook that tracks the mouse cursor position (x, y coordinates) within the page.
Return Values
Name | Type | Description |
---|---|---|
mouse.x | number | The horizontal (x) coordinate of the mouse cursor. |
mouse.y | number | The vertical (y) coordinate of the mouse cursor. |
Source Code
export const useMousePosition = () => { let x = $state(0); let y = $state(0); const updateMousePosition = (event) => { x = event.clientX; y = event.clientY; }; $effect(() => { window.addEventListener('mousemove', updateMousePosition); return () => { window.removeEventListener('mousemove', updateMousePosition); }; }); return { get x() { return x; }, get y() { return y; }, }; };
Mouse Position
X 0px
Y 0px
<script> import { useMousePosition } from "./useMousePosition.svelte"; let position = useMousePosition(); </script> {#snippet box({label, value})} <div class="box box-{label.toLowerCase()}"> <span class="label">{label}</span> <span class="value">{value}px</span> </div> {/snippet} <div class="container"> <span class="title">Mouse Position</span> {#key position} <div class="box-list"> {@render box({label: "X", value: position.x })} {@render box({label: "Y", value: position.y })} </div> {/key} </div> <style> .container { height:130px; display: flex; flex-direction:column; justify-content:center; align-items:center; gap:20px; } .title { font-weight:700; font-size:24px; } .box-list { display:flex; align-self:stretch; justify-content:center; gap:25px; } .box { background-color:rgba(255,255,255,.05); display:flex; flex-direction:column; align-items:center; gap:5px; padding:15px; border-radius:5px; flex-basis:150px; } .box .label { text-transform:uppercase; letter-spacing:1px; font-weight:700; text-transform:uppercase; font-size:12px; color:rgba(255,255,255,.8); } .box .value { font-weight:700; font-size:16px; } </style>