Access Event to Call Preventdefault from Custom Function Originating from Onclick Attribute of Tag

Access event to call preventdefault from custom function originating from onclick attribute of tag

I believe you can pass in event into the function inline which will be the event object for the raised event in W3C compliant browsers (i.e. older versions of IE will still require detection inside of your event handler function to look at window.event).

A quick example.

function sayHi(e) {   e.preventDefault();   alert("hi");}
<a href="http://google.co.uk" onclick="sayHi(event);">Click to say Hi</a>

How to prevent default event handling in an onclick method?

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 */
});

Handle links click with jquery

$("a").click(function(e){

// Do what all checks you need to do here
if(something is wrong)
{
// Do stuff here
e.preventDefault(); // Stop propagation of default event.
return false;
}

});

This way the data-transition will also work, becaue the default event will be stopped only when the validation fails.



Related Topics



Leave a reply



Submit