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
How to Get Jquery.Trigger('Click'); to Initiate a Mouse Click
How to Use Window.Postmessage Across Domains
How to Detect Whether an Iframe Is Loaded
How to Make Div Fixed After You Scroll to That Div
Get Unique Selector of Element in Jquery
Jquery Submit Form and Then Show Results in an Existing Div
How to Determine Which Submit Button Was Pressed, Form Onsubmit Event, Without Jquery
Scope of Sessionstorage and Localstorage
How to Open a New Window and Insert HTML into It Using Jquery
How to Sort Elements by Numerical Value of Data Attribute
Vuejs Error: the Client-Side Rendered Virtual Dom Tree Is Not Matching Server-Rendered
Casperjs/Phantomjs Doesn't Load Https Page
Parse Date Without Timezone JavaScript
How Does the New Operator Work in JavaScript