I want to trigger a hyperlink by hitting Enter using jQuery. I have the following html but all an Enter-stroke does is trigger the alert, it doesn’t navigate to the link. Clicking the link, however, does navigate to the new address. What am I missing?
I know my test function is working since the addClass/removeClass functions are working.
<html> <head> <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js'></script> <script type='text/javascript'> $(document).ready(function(){ $('a').click(function(event){ alert(this.href); }); }); function test(event){ if (event.keyCode == 13) { $('a').addClass('test'); $('a.one').trigger('click'); } else { $('a').removeClass('test');} } </script> <style type='text/css'> a.test { font-weight: bold; } </style> </head> <body onkeypress='test(event)'> <a class='one' href='http://jquery.com/'>jQuery</a> <br/> <a class='two' href='http://stackoverflow.com/'>stack overflow</a> </body> </html>
Add a window.location = this.href; to your click function. That should work.