How to prevent default event handling in an onclick method?
Solution 1:
Let your callback return false
and pass that on to the onclick
handler:
<a href="#" onclick="return callmymethod(24)">Call</a>
function callmymethod(myVal){
//doing custom things with myVal
//here I want to prevent default
return false;
}
To create maintainable code, however, you should abstain from using "inline Javascript" (i.e.: code that's directly within an element's tag) and modify an element's behavior via an included Javascript source file (it's called unobtrusive Javascript).
The mark-up:
<a href="#" id="myAnchor">Call</a>
The code (separate file):
// Code example using Prototype JS API
$('myAnchor').observe('click', function(event) {
Event.stop(event); // suppress default click behavior, cancel the event
/* your onclick code goes here */
});
Solution 2:
In my opinion the answer is wrong! He asked for event.preventDefault();
when you simply return false; it calls event.preventDefault();
AND event.stopPropagation();
as well!
You can solve it by this:
<a href="#" onclick="callmymethod(event, 24)">Call</a>
function callmymethod(e, myVal){
//doing custom things with myVal
//here I want to prevent default
e = e || window.event;
e.preventDefault();
}
Solution 3:
Try this (but please use buttons for such cases if you don't have a valid href
value for graceful degradation)
<a href="#" onclick="callmymethod(24); return false;">Call</a>
Solution 4:
You can catch the event and then block it with preventDefault() -- works with pure Javascript
document.getElementById("xyz").addEventListener('click', function(event){
event.preventDefault();
console.log(this.getAttribute("href"));
/* Do some other things*/
});