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

I have links like this:

<a href="#" onclick="myfunc({a:1, b:'hi'})" />click</a>
<a href="#" onclick="myfunc({a:3, b:'jo'})" />click</a>

And I would like to do a preventDefault() inside myfunc(), because a # will be added in the address bar when clicking on the link (without doing return false; or href='javascript:void(0);')

Is this possible? Can I get the event inside myfunc()

This question is related to javascript jquery html

The answer is


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

I think when we use onClick we want to do something different than default. So, for all your links with onClick:

$("a[onClick]").on("click", function(e) {
  return e.preventDefault();
});

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.


e.preventDefault(); from https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault

Or have return false from your method.


Can you not just remove the href attribute from the a tag?


Try this:

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

You can access the event from onclick like this:

<button onclick="yourFunc(event);">go</button>

and at your javascript function, my advice is adding that first line statement as:

function yourFunc(e) {
    e = e ? e : event;
}

then use everywhere e as event variable


Simple!

onclick="blabla(); return false"

Without any JS library or jQuery. To open a nice popup window if possible. Fails safely to normal link open.

<a href="https://acme.com/" onclick="onclick="openNewWindow(event, this.href);">...</a>

And the helper function:

function openNewWindow(event, location) {
  if (event.preventDefault && event.stopImmediatePropagation) { 
    event.preventDefault(); 
    event.stopImmediatePropagation(); 
  } else {
    event.returnValue = false; 
  }
  window.open(location, 'targetWindow', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=800,height=450');
}

Add a unique class to the links and a javascript that prevents default on links with this class:

<a href="#" class="prevent-default" 
   onclick="$('.comment .hidden').toggle();">Show comments</a>

<script>
  $(document).ready(function(){

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment