views:

20391

answers:

3

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.

+21  A: 

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:

http://docs.jquery.com/Events_(Guide)#event.preventDefault.28__.29

Davide Gualano
+4  A: 

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
see my comment on the answer above, i ask where...
Pickledegg
yeah, i think i was answering what i thought your intent was instead of the question :)
Kent Fredric
+1  A: 

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;
    }
This way will lose the :hover attribute in the bad browsers (ie family)
DaNieL