<body>
<button onclick="myFunction()">CLICK</button>
<script>
function myFunction(event) {
// do something based on the value of the event's property
}
</script>
</body>
<body>
<button id="myButton">CLICK</button>
<script>
var button = document.getElementById("myButton");
button.addEventListener("click", myFunction);
function myFunction(event) {
// do something based on the value of the event's property
}
</script>
</body>
I might add click events to the button by the two methods above.
I want to modify some properties of the event object that myFunction
will receive before it executes.
For example, in the click event, the event has clientX
and clientY
properties, and assuming the original values are 100 and 100, I want them to be 150 and 150 (how they change is determined by certain conditions) and the other property values to be the same as the original values.
Is there any way to achieve this?
Additional Information
I needed the modified event because for some reason I added the scale
, width
style attributes to the body element, which made the position-related coordinate points calculate incorrectly.
Some events related to coordinate points, such as click
, drag
, are not behaving properly.
Basically, every point-related event object has to be fixed, most notably MouseEvent
, PointerEvent
.
According to @Mr. Polywhirl, I need to write a function to handle the event object first, and then call the actual callback in the handling function, which is more replicated.
Is it possible to achieve a senseless modification by modifying the addEventListener
on the prototype?
If it works, how would a binding like <button onclick="myFunction(event)">CLICK</button>
achieve the same event modification?
try this
Press F12 on this page to open the console, and type document.body.style="scale: 0.8;width: 125%;transform-origin: 0 0;"
in the console.
Then click on the recent inbox messages
at the top of the page, which is probably what you’re seeing.
2
Answers
You will need to make a copy of the event, since the
clientX
andclientY
properties are read-only.Intercept the event in another function, modifiy the event, and send it into the original handler.
If you want to properly clone the event, you can try:
A generic solution with
Proxy
to modify an event.You can create a global getter object to fix your event values, in the snippet there’s a correction to make
event.clientX/Y
to have the pointer coordinates relative to the target element for all elements inside a container element of choice: