MENU
Preventing Default Behaviour
You can stop the default action of an HTML element by using event.preventDefault(). The default action can also be stopped by executing 'return false;' on the inline event attribute.
In this example, clicking the link or the checkbox won't change or trigger anything. Only small letters can be entered in the textbox.
RESETRUNFULL
RESETRUNFULL
<!DOCTYPE html><html><head>
<script>
function clk(e){e.preventDefault();}
function prs(e){
var charCode = e.charCode;
if (charCode < 97 || charCode > 122) {
e.preventDefault();
alert(
"Please use lowercase letters only."
+ "\n" + "charCode: " + charCode + "\n"
);
}
}
</script></head><body>
<a href="http://google.com" onclick="return false;">
Google</a>
<input type='checkbox' onclick="clk(event)"/>
<input type='text' onkeypress="prs(event)"/></body></html>
If you define the event handler programmatically, such as by using .addEventListener(), you cannot prevent the default behavior by running 'return false;' in the handler function, as you do inside an inline event attribute. In such cases, event.preventDefault()remains the sole method to stop the default behavior.