0

Hey guys am new to javascript web development.I have been through preventDefault() through my code.But when i used it it returns the error ..My code

<html>
<body>
function preventDef(event) {
  event.preventDefault();
}

 document.querySelector('a').addEventListener("click", 
preventDef(event),false);

</script>

<a href="www.google.com">click here</a>
</body>
</html>

When i use this code and clicked on the link it redirects me to google.com ..what i need is the event must be blocked my preventDefault() function..

Hope you guys can help me out ..Thanks

1 Answers1

1

You are calling the preventDef function instead of passing it by reference.

document.querySelector('a').addEventListener("click", preventDef, false);
//                                                              ^^^ don't call the function

EDIT: Another issue is that you are running this before the DOM is ready. You need to move the <script> tag down to be after the <a>.

<html>
<body>
<a href="www.google.com">click here</a>
<script>
// ^^ did you miss an opening script?
function preventDef(event) {
  event.preventDefault();
}

 document.querySelector('a').addEventListener("click", preventDef, false);
//                                                              ^^^ don't call the function

</script>

</body>
</html>
Scimonster
  • 30,695
  • 8
  • 67
  • 84