148

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()

Shashanth
  • 4,995
  • 7
  • 41
  • 51
Omu
  • 69,856
  • 92
  • 277
  • 407

11 Answers11

192

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).
totymedli
  • 29,531
  • 22
  • 131
  • 165
Russ Cam
  • 124,184
  • 33
  • 204
  • 266
  • 7
    ok, I see all I had to do is to put my parameter second `myfunc(event, {a:123, b:"asdas"})` – Omu Dec 23 '11 at 10:01
  • 3
    @Omu The passed-in argument, event, can be in any place, don't have to be the first one, as long as it is in the right place of the defined parameter list for the function. For example, `function myfunc(o, e) {...}`, then it can be called as `myfunc({a:1, b:'hi'}, event)`. – cateyes Nov 19 '14 at 23:47
  • 3
    I think you don't have to explicitly pass and capture the event object. You can simply refer to it in the function. Can someone please confirm? I mean, this code without the event should also work: `function sayHi() { event.preventDefault(); alert("hi"); }` – K Vij Nov 27 '19 at 02:20
136

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.

JuLo
  • 1,501
  • 1
  • 9
  • 11
  • Could just use server side tech to re-write that link if cache busting is all you're after. – mpen Nov 04 '14 at 23:03
  • It would be better, but I don't have access to the server side code. Working with what I've got. – JuLo Nov 05 '14 at 00:27
10

Try this:

<script>
    $("a").click(function(event) {
        event.preventDefault(); 
    });
</script>
YakovL
  • 7,557
  • 12
  • 62
  • 102
Suave Nti
  • 3,721
  • 11
  • 54
  • 78
  • this requires a – somid3 Jun 04 '12 at 01:13
  • 1
    It also requires jQuery, which whilst might be present shouldn't be a prerequisite. – Irregular Shed Aug 05 '14 at 11:12
  • 1
    Also disagree here, A simple parse to an inline function is more effective and less code. – Shannon Hochkins Dec 04 '14 at 23:58
  • 1
    @somid3, while jQuery is not *necessary*, if you're worried about performance, you can use a single delegated event handler so that you're only attaching a single listener for all anchors on the page like this: `$("body").on("click","a",function(e) { e.preventDefault() });`. In either case, neither solution is going to meaningfully impact performance. – KyleMit Nov 17 '16 at 20:50
6

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

Leigh Ciechanowski
  • 1,297
  • 17
  • 33
  • 1
    yes, that's an option too, though by default the link will not have underline, and if javascript is turned off there isn't going to be href to go to – Omu Dec 23 '11 at 09:50
6
<script type="text/javascript">
$('a').click(function(){
   return false;
});
<script>
Aram Mkrtchyan
  • 2,690
  • 4
  • 31
  • 47
  • 2
    This applies to every anchor, and will break all links, also requires javascript to be inserted on the page as well as jQuery. – Shannon Hochkins Dec 04 '14 at 23:56
  • Plus, when using jQuery, `return false` is not recommended as it will also prevent all other event handlers on that element from running, and stop the event from bubbling up to higher elements. – Stijn de Witt Nov 06 '15 at 13:22
6

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>
aaandre
  • 2,502
  • 5
  • 33
  • 46
5

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();
});
Ronan
  • 127
  • 2
  • 7
3

Simple!

onclick="blabla(); return false"
Pang
  • 9,564
  • 146
  • 81
  • 122
Jake
  • 39
  • 1
3

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

gdarcan
  • 595
  • 5
  • 8
2

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');
}
0

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

Or have return false from your method.

rahul singh Chauhan
  • 323
  • 1
  • 4
  • 15