preventDefault() The preventDefault() method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
preventDefault() method stops the default action of an element from happening. For example: Prevent a submit button from submitting a form. Prevent a link from following the URL.
See, the event.preventDefault is a javascript function and is independent of angular version. However the binding used for (ngSubmit) in angularjs will change but the event.preventdefault would remain the same. You can try passing $event on (click) of a button as a parameter of any function.Ex. (
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>
It's suggested that you do not use return false
, as 3 things occur as a result:
So in this type of situation, you should really only use event.preventDefault();
Archive of article - jQuery Events: Stop (Mis)Using Return False
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>
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 ;)
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With