[Javascript] preventDefault() on an <a> tag


Answers

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

Question

I have some html/jquery that slides a div up and down to show/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>

and my jquery...

$('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 that preventDefault() is not a function.




after several operations, when the page should finally go to 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;
          });



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




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




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>



Links