Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent default event handling in an onclick method?

Tags:

javascript

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 } 
like image 411
coure2011 Avatar asked Aug 14 '11 11:08

coure2011


People also ask

How do I stop a default Click event?

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.

How can we prevent default behavior in react?

We can prevent this default behaviour by making a small modification to the definition of the handleSubmit function. We call a preventDefault on the event when submitting the form, and this will cancel the default event behavior (browser refresh) while allowing us to execute any code we write inside handleSubmit.

Which event object method can we use to stop a default event action of an element?

The event. preventDefault() method stops the default action of an element from happening.

What is the default action of a click event?

A click on a form submit button – initiates its submission to the server. Pressing a mouse button over a text and moving it – selects the text.


2 Answers

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 */ }); 
like image 107
Linus Kleen Avatar answered Oct 05 '22 03:10

Linus Kleen


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(); } 
like image 34
Wawa Avatar answered Oct 05 '22 02:10

Wawa