Skip to content

Instantly share code, notes, and snippets.

@scharfie
Last active January 21, 2026 16:17
Show Gist options
  • Select an option

  • Save scharfie/b038a77c9cc6ed3b1b05310f888e45c0 to your computer and use it in GitHub Desktop.

Select an option

Save scharfie/b038a77c9cc6ed3b1b05310f888e45c0 to your computer and use it in GitHub Desktop.
mouse crosshair
// example: https://jsfiddle.net/h4gbru7o/
function InstallMouseCrossHair() {
const color = "#333";
const size = 24;
const sizePx = size + 'px';
const sizeHalf = size > 1 ? size / 2 : 0;
const xOffset = 0;
const yOffset = 0;
let frameRequested = false;
const xBar = document.createElement('div');
const yBar = document.createElement('div');
const container = document.createElement('div');
Object.assign(xBar.style, { visibility: 'hidden', background: color, position: 'fixed', width: '100%', height: sizePx });
Object.assign(yBar.style, { visibility: 'hidden', background: color, position: 'fixed', width: sizePx, height: '100%' });
Object.assign(container.style, { opacity: 0.6, position: 'fixed', top: 0, left: 0, 'mix-blend-mode': 'difference' });
container.appendChild(xBar);
container.appendChild(yBar);
document.body.appendChild(container);
function toggleVisibility(event) {
// only show the crosshair when CTRL key is pressed
let visibility = event.ctrlKey ? 'visible' : 'hidden';
xBar.style.visibility = visibility;
yBar.style.visibility = visibility;
};
function handleMove(event) {
// we don't want to queue up multiple animation frame requests
if (frameRequested) { return; }
frameRequested = true;
let x = event.clientX - sizeHalf + xOffset;
let y = event.clientY - sizeHalf + yOffset;
window.requestAnimationFrame(() => {
xBar.style.transform = `translateY(${y}px)`;
yBar.style.transform = `translateX(${x}px)`;
frameRequested = false;
});
}
window.addEventListener('keydown', toggleVisibility);
window.addEventListener('keyup', toggleVisibility);
window.addEventListener('mousemove', handleMove);
}
window.addEventListener('DOMContentLoaded', InstallMouseCrossHair);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment