Dispatch Events
by Hugo Vale Pereira
HTML
<div id="my-element">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
CSS
#my-element{
width:200px;
height: 200px;
background: grey;
overflow: auto;
scroll-snap-type: mandatory;
}
.box{
width: 200px;
height: 200px;
background: linear-gradient(217deg, rgb(255 0 0 / 0.8), orange);
}
JavaScript
const myElement = document.getElementById("my-element");
myElement.addEventListener("wheel", (e) => {
console.log("wheel");
console.log(e.isTrusted)
});
myElement.addEventListener("click", (e) => {
const nE = new WheelEvent("wheel", {
isTrusted:true,
bubbles: true,
cancelable: true,
view: e.currentTarget.ownerDocument.defaultView,
deltaY: 10,
});
let dispatch = e.target.dispatchEvent(nE);
});
myElement.addEventListener("scrollend", () => {
console.log("scrollend");
});
myElement.addEventListener("touchstart", function (event) {
// Prevent default actions like scrolling
event.preventDefault();
// Get the first touch point
const touch = event.touches[0];
// Log the touch coordinates
console.log(`Touch started at x: ${touch.clientX}, y: ${touch.clientY}`);
});
function onTouch(event) {
event.preventDefault();
if (
event.touches.length > 1 ||
(event.type === "touchend" && event.touches.length > 0)
)
return;
let type;
let touch;
switch (event.type) {
case "touchstart":
type = "mousedown";
touch = event.changedTouches[0];
break;
case "touchmove":
type = "mousemove";
touch = event.changedTouches[0];
break;
case "touchend":
type = "mouseup";
touch = event.changedTouches[0];
break;
}
const newEvent = new MouseEvent(type, {
bubbles: true,
cancelable: true,
view: event.originalTarget.ownerDocument.defaultView,
detail: 0,
screenX: touch.screenX,
screenY: touch.screenY,
clientX: touch.clientX,
clientY: touch.clientY,
ctrlKey: event.ctrlKey,
altKey: event.altKey,
shiftKey: event.shiftKey,
metaKey: event.metaKey,
button: 0,
relatedTarget: null,
});
event.originalTarget.dispatchEvent(newEvent);
}