preventDefault() on an <a> tag
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.
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
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>