Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What is the use of event preventDefault () method?

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.

What is an onClick attribute?

The onClick attribute is an event handler that instructs the browser to run a script when the visitor clicks a button.

Is it bad to use onClick attribute?

It's a new paradigm called "Unobtrusive JavaScript". The current "web standard" says to separate functionality and presentation. It's not really a "bad practice", it's just that most new standards want you to use event listeners instead of in-lining JavaScript.


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>
  1. Run it as is and notice that the link does no redirect to Google after the alert.
  2. Then, change the event passed into the onclick handler to something else like e, click run, then notice that the redirection does take place after the alert (the result pane goes white, demonstrating a redirect).

The simplest solution simply is:

<a href="#" onclick="event.preventDefault(); myfunc({a:1, b:'hi'});" />click</a>

It's actually a good way of doing cache busting for documents with a fallback for no JS enabled browsers (no cache busting if no JS)

<a onclick="
if(event.preventDefault) event.preventDefault(); else event.returnValue = false;
window.location = 'http://www.domain.com/docs/thingy.pdf?cachebuster=' + 
Math.round(new Date().getTime() / 1000);" 
href="http://www.domain.com/docs/thingy.pdf">

If JavaScript is enabled, it opens the PDF with a cache busting query string, if not it just opens the PDF.


Try this:

<script>
    $("a").click(function(event) {
        event.preventDefault(); 
    });
</script>

<script type="text/javascript">
$('a').click(function(){
   return false;
});
<script>