Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using preventDefault in onclick doesn't work

Tags:

javascript

Can anyone tell me why the code below doesn't seem to prevent the link from doing its thing? I know I can just use onclick="return false", but it should work with preventDefault, right? I tried onclick="function(e){this.preventDefault()}" and onclick="this.preventDefault()", but no love.

<!doctype html>  
<html lang="en">  
    <head>  
        <meta charset="utf-8">  
        <title>Test</title>  
    </head>  
    <body> 
        <a href="http://www.google.com" onclick="function(e){e.preventDefault()}">Google Search</a>
    </body>  
</html>
like image 621
JulianJohannesen Avatar asked Oct 15 '25 03:10

JulianJohannesen


1 Answers

Remove function(e){. When you put function(e){} there, that means creating a function but not running it.

Demo: http://jsfiddle.net/DerekL/RnngR/

Do it like this:

<a href="http://www.google.com" onclick="event.preventDefault();">Google Search</a>
like image 57
Derek 朕會功夫 Avatar answered Oct 16 '25 16:10

Derek 朕會功夫



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!