How to prevent default in an onclick method? I have a method in which I am also passing a custom value
<a href="#" onclick="callmymethod(24)">Call</a>
function callmymethod(myVal){
//doing custom things with myVal
//here I want to prevent default
}
This question is related to
javascript
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();
}
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*/
});
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>
Give a class or id to the element and use jquery function unbind();
$(".slide_prevent").click(function(){
$(".slide_prevent").unbind();
});
Just place "javascript:void(0)", in place of "#" in href tag
<a href="javascript:void(0);" onclick="callmymethod(24)">Call</a>
This worked for me
<a href="javascript:;" onclick="callmymethod(24); return false;">Call</a>
Another way to do that is to use the event
object inside the attribute onclick
(without the need to add an additional argument to the function to pass the event)
function callmymethod(myVal){_x000D_
console.log(myVal);_x000D_
}
_x000D_
<a href="#link" onclick="event.preventDefault();callmymethod(24)">Call</a>
_x000D_
If you need to put it in the tag. Not the finest solution, but it will work.
Make sure you put the onclick event in front of the href. Only worked for my this way.
<a onclick="return false;" href="//www.google.de">Google</a>
It would be too tedious to alter function usages in all html pages to return false
.
So here is a tested solution that patches only the function itself:
function callmymethod(myVal) {
// doing custom things with myVal
// cancel default event action
var event = window.event || callmymethod.caller.arguments[0];
event.preventDefault ? event.preventDefault() : (event.returnValue = false);
return false;
}
This correctly prevents IE6, IE11 and latest Chrome from visiting href="#"
after onclick event handler completes.
Credits:
Source: Stackoverflow.com