104

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
}
Ry-
  • 218,210
  • 55
  • 464
  • 476
coure2011
  • 40,286
  • 83
  • 216
  • 349

13 Answers13

133

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 */
});
Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
  • 1
    @AamirAfridi Yes, it is working. You should adjust your fiddle and change `onLoaded` to `no wrap`. Or simply write your own .html markup instead. – Linus Kleen Jan 24 '13 at 10:41
  • 1
    Please see answer below! "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!" – Ravindranath Akila Sep 03 '13 at 13:05
  • 1
    To be fastidious, the OP's question never mentions `preventDefault`, the question is, how to *"prevent [the] default click"*. – Linus Kleen Sep 03 '13 at 17:03
  • 1
    @LinusKleen, say also please, how to prevent click in this [case](http://jsfiddle.net/9JvdG/) – vp_arth Apr 11 '14 at 07:53
  • 1
    @vp_arth Use "CSS click through" for this. Look at [this question](http://stackoverflow.com/questions/3680429/click-through-a-div-to-underlying-elements). – Linus Kleen Apr 11 '14 at 17:56
  • @LinusKleen, thanks, but I need to stop parent event, when for child own event binded; I already found `stopImmediatePropogation` method for this – vp_arth Apr 11 '14 at 18:03
  • извините, that won't work. That method you found won't work. Since you're using inline event handlers. Would they have been dynamically declared, it might just work. – Linus Kleen Apr 11 '14 at 18:11
  • 1
    I upvoted this because of the warning about maintainable code. This creates problems when you want to use `preventDefault` later. – Alex W Jan 15 '15 at 21:44
  • 1
    "abstain from using inline Javascript", is not always applicable and there are many different frameworks (ie Angular) where inline javascript calls are very important to the flow of the application. – Michael Artman Feb 05 '21 at 15:01
67

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();
}
Nigel Fds
  • 803
  • 2
  • 12
  • 29
Wawa
  • 679
  • 5
  • 2
56

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>
Aamir Afridi
  • 6,364
  • 3
  • 42
  • 42
15

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*/
});
Andreas Karz
  • 390
  • 3
  • 6
13

Just place "javascript:void(0)", in place of "#" in href tag

<a href="javascript:void(0);" onclick="callmymethod(24)">Call</a>
Rafay
  • 131
  • 1
  • 2
9

This worked for me

<a href="javascript:;" onclick="callmymethod(24); return false;">Call</a>
Pixelomo
  • 6,373
  • 4
  • 47
  • 57
7

You can use:

event.stopPropagation();

https://dom.spec.whatwg.org/#dom-event-stoppropagation

Koray Tugay
  • 22,894
  • 45
  • 188
  • 319
5

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){
    console.log(myVal);
}
<a href="#link" onclick="event.preventDefault();callmymethod(24)">Call</a>
h3t1
  • 1,126
  • 2
  • 18
  • 29
5

Several different answers. Even after so many years, the question is still relevant. Therefore, here is the compilation:

// 1
function myFn1 (e, value) {
    console.log('value:', value)
    e.preventDefault();
}

// 2
function myFn2 (value) {
    console.log('value:', value)
    return false;
}

// 3,5,6,7
function myFn3 (value) {
    console.log('value:', value)    
}

// 4
document.getElementById("clicki-1").addEventListener('click', function(event){
    event.preventDefault();
    console.log('value:',this.getAttribute("data-value"));
});
<h3>onclick Attribute</h3>
<div>
  <a href="/hello" onclick="myFn1(event, 42)">Click 1</a>
</div>

<div>
  <a href="/hello" onclick="return myFn2(42)">Click 2</a>
</div>

<div>
  <a href="/hello" onclick="myFn3(42); return false;">Click 3</a>
</div>

<h3>EventListener (addEventListener)</h3>
<div>
  <a href="/hello" id="clicki-1" data-value="42">Click 4</a>
</div>

<h3>onclick Attribute without linkaddress when hovering</h3>
<div>  
  <a href="javascript:;" onclick="event.preventDefault(); myFn3(42)">Click 5</a>
</div>

<div>  
  <a href="javascript:void(0);" onclick="myFn3(42)">Click 6</a>
</div>

<div>  
  <a href="javascript:;" onclick="myFn3(42)">Click 7</a>
</div>

<h5>Set Anchor Hashtag</h5>
<div>  
  <a href="#" onclick="myFn3(42)">Click 8</a>
</div>

I prefer the variant 2 with return false; if it has to go quickly. And otherwise variant 4 (AddEventListener).

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
0

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:

Vadzim
  • 24,954
  • 11
  • 143
  • 151
0

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>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Matix
  • 99
  • 2
  • 9
0

Consider using a form instead of a link. Then, all you really need to do is add:

<input type="submit" onclick="event.preventDefault();">

You probably want to handle it though so in total you'd probably do something more like this:

function myFunction() {
  if (confirm("Are you sure you want to ...? This action cannot be undone.")) {
    document.getElementById("myForm").submit();
  }
}
<form method="post" action="/test" id="myForm">
  <input type="submit" onclick="event.preventDefault();myFunction();">
</form>

This allows the user to click ok to proceed or cancel to not have it submit the form.

Michael M.
  • 10,486
  • 9
  • 18
  • 34
-3

Give a class or id to the element and use jquery function unbind();

$(".slide_prevent").click(function(){
                $(".slide_prevent").unbind();
              });
user46487
  • 644
  • 6
  • 8