Modify the definition of the function check_me as::
function check_me(ev) {
Now you can access the methods and parameters of the event, in your case:
ev.preventDefault();
Then, you have to pass the parameter on the onclick in the inline call::
<button type="button" onclick="check_me(event);">Click Me!</button>
A useful link to understand this.
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function check_me(ev) {
ev.preventDefault();
alert("Hello World!")
}
</script>
</head>
<body>
<button type="button" onclick="check_me(event);">Click Me!</button>
</body>
</html>
Although the above is the direct answer to the question (passing an event object to an inline event), there are other ways of handling events that keep the logic separated from the presentation
addEventListener
:<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<button id='my_button' type="button">Click Me!</button>
<!-- put the javascript at the end to guarantee that the DOM is ready to use-->
<script type="text/javascript">
function check_me(ev) {
ev.preventDefault();
alert("Hello World!")
}
<!-- add the event to the button identified #my_button -->
document.getElementById("my_button").addEventListener("click", check_me);
</script>
</body>
</html>
Both of the above solutions are fine for a small project, or a hackish quick and dirty solution, but for bigger projects, it is better to keep the HTML separated from the Javascript.
Just put this two files in the same folder:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<button id='my_button' type="button">Click Me!</button>
<!-- put the javascript at the end to guarantee that the DOM is ready to use-->
<script type="text/javascript" src="example.js"></script>
</body>
</html>
function check_me(ev) {
ev.preventDefault();
alert("Hello World!")
}
document.getElementById("my_button").addEventListener("click", check_me);