165

I have some HTML and jQuery that slides a div up and down to show or hide` it when a link is clicked:

<ul class="product-info">
  <li>
    <a href="#">YOU CLICK THIS TO SHOW/HIDE</a>
    <div class="toggle">
      <p>CONTENT TO SHOW/HIDE</p>
    </div>
  </li>
</ul>
$('div.toggle').hide();
$('ul.product-info li a').click(function(event){
  $(this).next('div').slideToggle(200);
}

My question is: How do I use preventDefault() to stop the link acting as a link and adding "#" to the end of my URL & jumping to the top of the page?

I can't figure out the right syntax, I just keep getting an error saying

preventDefault() is not a function.

John C
  • 3,052
  • 3
  • 34
  • 47
Chris J Allen
  • 18,970
  • 20
  • 76
  • 114

12 Answers12

210

Try something like:

$('div.toggle').hide();
$('ul.product-info li a').click(function(event) {
    event.preventDefault();
    $(this).next('div').slideToggle(200);
});

Here is the page about that in the jQuery documentation

Aliaksandr Sushkevich
  • 11,550
  • 7
  • 37
  • 44
Davide Gualano
  • 12,813
  • 9
  • 44
  • 65
72

Set the href attribute as href="javascript:;"

<ul class="product-info">
  <li>
   <a href="javascript:;">YOU CLICK THIS TO SHOW/HIDE</a>
  <div class="toggle">
    <p>CONTENT TO SHOW/HIDE</p>
  </div>
 </li>
</ul>
Aliaksandr Sushkevich
  • 11,550
  • 7
  • 37
  • 44
Musaddiq Khan
  • 1,837
  • 18
  • 16
  • Nice little gem for anchors --thanks! Could anyone describe why this works? – justinpage Oct 24 '14 at 00:42
  • 9
    @KLVTZ `href` attribute of anchor tag (`a`) may not be empty... But we can set it to `javascript:`, that is legal/valid. We then enter for `` just an empty statement by adding a semicolon. This way the link does nothing. – Stijn de Witt Nov 06 '15 at 13:17
  • 1
    Thanks a lot! This allowed me to implement a back button functionality (remembering the state set by pushState() accross pages) into CalePHP's breadcrumbs like this $this->Html->addCrumb('Sessions', 'javascript:window.history.back();'); – Patronaut Apr 22 '18 at 09:06
  • This is an old answer but was still bad advice even then. Use JavaScript to attach event handlers to elements, not HTML. And don't abuse HTML by using an anchor element with an `href` attribute (which should navigate the user somewhere else) to initiate behavior (something that buttons are meant for). – Heretic Monkey Jan 23 '22 at 23:37
44

It's suggested that you do not use return false, as 3 things occur as a result:

  1. event.preventDefault();
  2. event.stopPropagation();
  3. Stops callback execution and returns immediately when called.

So in this type of situation, you should really only use event.preventDefault();

Archive of article - jQuery Events: Stop (Mis)Using Return False

KyleMit
  • 30,350
  • 66
  • 462
  • 664
RPL
  • 3,500
  • 2
  • 21
  • 28
39

1 - Easy way:

<a href="javascript:;">Click Me</a>

2 - using void(0):

<a href="javascript:void(0);">Click Me</a>

3 - Using preventDefault():

<a href='#' onclick="event.preventDefault()">Click Me</a>

4 - Yet another way of doing this in Javascript using inline onclick, IIFE, event and preventDefault():

<a href='#' onclick="(function(e){e.preventDefault();})(event)">Click Me</a>
A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128
  • 1
    Hi, or simply `Click Me` – Ermac Jul 12 '20 at 02:07
  • @ankabot yup. I believe this is in some other answers though. I just wanted to add an answer with a different way not mentioned. Also to show different way of doing thing in Javascript. (there are unlimited ways to do things in JS!). The top answers are easier to read and more practical. This is an just for theory not practice :) – A-Sharabiani Feb 03 '21 at 19:13
13

Alternatively, you could just return false from the click event:

 $('div.toggle').hide();
 $('ul.product-info li a').click(function(event){
  $(this).next('div').slideToggle(200);
+ return false; 
 });

Which would stop the A-Href being triggered.

Note however, for usability reasons, in an ideal world that href should still go somewhere, for the people whom want to open link in new tab ;)

Kent Fredric
  • 56,416
  • 14
  • 107
  • 150
  • 1
    yeah, i think i was answering what i thought your intent was instead of the question :) – Kent Fredric Nov 05 '08 at 17:28
  • 1
    For what its worth, many years ago it was touted that you should return -1 to prevent the href from being triggered. I don't think that works in ANY browsers anymore, and you must "return false" to prevent the page jumping. – Randy Jun 12 '19 at 19:20
13

This is a non-JQuery solution I just tested and it works.

<html lang="en">
<head>
<script type="text/javascript">
addEventListener("load",function(){
    var links= document.getElementsByTagName("a");
    for (var i=0;i<links.length;i++){
        links[i].addEventListener("click",function(e){
        alert("NOPE!, I won't take you there haha");
        //prevent event action
        e.preventDefault();
        })
    }
}); 

</script>
</head>
<body>
<div>
<ul>
    <li><a href="http://www.google.com">Google</a></li>
    <li><a href="http://www.facebook.com">Facebook</a></li>
    <p id="p1">Paragraph</p>
</ul>
</div>
<p>By Jefrey Bulla</p>
</body>
</html>
Jefrey Bulla
  • 181
  • 2
  • 5
11
<ul class="product-info">
  <li>
    <a href="javascript:void(0);">YOU CLICK THIS TO SHOW/HIDE</a>
      <div class="toggle">
        <p>CONTENT TO SHOW/HIDE</p>
      </div>
  </li>
</ul>

Use

javascript:void(0);

HATCHA
  • 600
  • 1
  • 8
  • 15
  • @AhmadSharif I have tested on FF 40.0.3 and IE 11 today, there are still work. – HATCHA Aug 31 '15 at 04:37
  • 1
    I think void(0) can be ugly/confusing to users, who can see it when they hover the link. You can actually put any valid JS, so I like to put a comment that describes what it does. e.g. `href="javascript:// Send Email"` – colllin Nov 10 '16 at 22:10
  • This is an old answer but was still bad advice even then. Use JavaScript to attach event handlers to elements, not HTML. And don't abuse HTML by using an anchor element with an `href` attribute (which should navigate the user somewhere else) to initiate behavior (something that buttons are meant for). – Heretic Monkey Jan 23 '22 at 23:38
6

After several operations, when the page should finally go to <a href"..."> link you can do the following:

jQuery("a").click(function(e){
    var self = jQuery(this);
    var href = self.attr('href');
    e.preventDefault();
    // needed operations

    window.location = href;
});
Deitsch
  • 1,610
  • 14
  • 28
1nstinct
  • 1,745
  • 1
  • 26
  • 30
  • 1
    Why do `preventDefault`, and then do the default action yourself? Just do what you need to add, and let the default still take place. – nathanvda Jan 13 '15 at 18:25
5

You can make use of return false; from the event call to stop the event propagation, it acts like an event.preventDefault(); negating it. Or you can use javascript:void(0) in href attribute to evaluate the given expression and then return undefined to the element.

Returning the event when it's called:

<a href="" onclick="return false;"> ... </a>

Void case:

<a href="javascript:void(0);"> ... </a>

You can see more about in: What's the effect of adding void(0) for href and 'return false' on click event listener of anchor tag?

Community
  • 1
  • 1
RPichioli
  • 3,245
  • 2
  • 25
  • 29
5

If stopping the propagation of the event doesn't bother you, just use

return false;

at the end of your handler. In jQuery it prevents the default behaviour and it stop the event bubbling.

sebarmeli
  • 17,949
  • 7
  • 35
  • 40
5

Why not just do it in css?

Take out the 'href' attribute in your anchor tag

<ul class="product-info">
  <li>
    <a>YOU CLICK THIS TO SHOW/HIDE</a>
    <div class="toggle">
      <p>CONTENT TO SHOW/HIDE</p>
    </div>
  </li>
</ul>

In your css,

  a{
    cursor: pointer;
    }
1

In Javascript you can use it

window.event.preventDefault();

It works in my case. write the above line into your function.