โจclick to move ball
browser โฉ event โฉ type โฉ mouse โฉ click โฉ example โฉ click to move ball
replit โฉ click to move ball , require โฉ Node+ext, MouseEvent+ext, Element+boxes
const { log } = console
// โญ๏ธ import
import { $ } from './js/ext/Node_ext.js'; // ๐ Node + ext
import { rect } from './js/ext/Rect.js'; // ๐ Rect
import { } from './js/ext/Element+boxes.js'; // ๐ Element + boxes
import { } from './js/ext/MouseEvent+ext.js'; // ๐ MouseEvent + ext
// --------------------------------------------------------------------
// elements
const ball = $("#ball"); // ๐ Node + ext
const field = $("#field");
const info = $("#info");
const ballSize = ball.paddingBox.size; // ๐ Element + boxes
const {width: w, height: h} = field.paddingBox.size;
const dx = ballSize.width/2;
// โญ๏ธ event handlers
// -------------------------------------------------------
// field.onclick
field.onclick = (event) => {
// calculate ball's (constrained) new origin
const {x, y} = event
// mouse cursor point
.pointInElement(field)
// constrain center in "inset" rect
.clampInRect(rect(dx, dx, w-2*dx, h-2*dx)) // ๐ Rect
// translate to top left corner
.plus(ballSize.vector.times(-0.5));
// update ball's position
ball.style.left = x + 'px';
ball.style.top = y + 'px';
};
// document.onmousemove
document.onmousemove = (e) => {
info.innerHTML = `โข screen: ${e.pointInScreen}<br>` // ๐ MouseEvent + ext
+ `โข page : ${e.pointInPage}<br>`
+ `โข viewport: ${e.pointInViewport}<br>`
+ `โข field: ${e.pointInElement(field)}`;
};
Event โฉ UIEvent โฉ MouseEvent โฉ
Last updated