It's been a while that PyCharm (I suppose it's the same with WebStorm and other JetBrains IDEs) raise a weak warning on the event
variables I use in my code.
For instance in the following code
<div id="my-div" onclick="event.preventDefault();">...</div>
PyCharm displays this message "Deprecated symbol used, consult docs for better alternative".
The problem seems to be that the event
variable refers to Window.event
, and according to MDN Web Docs:
You should avoid using this property in new code, and should instead use the Event passed into the event handler function. This property is not universally supported and even when supported introduces potential fragility to your code.
I know that a correct workaround would be to write in a javascript tag:
document.getElementById("my-div").addEventListener("click", function(event) {
console.log("And use this " + event + " instead");
});
I am just wondering what would be, if it exists, the correct way to use events in the HTML code (onclick
attribute).
Thank you in advance!
Just pass event to a callback using it inside in the JS side:
function preventDefault(event) {
event.preventDefault();
}
<div id="my-div" onclick="preventDefault(event)">Click me</div>
Or you can call it in the HTML in a closure
<div id="my-div" onclick="(function(event){event.preventDefault()})(event)">Click me</div>
I am strongly suggesting you to use the first option and not the latter