tags:

views:

462

answers:

2

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"&gt;&lt;/script&gt;
 <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/"&gt;jQuery&lt;/a&gt;
 <br/>
 <a class="two" href="http://stackoverflow.com/"&gt;stack overflow</a>
</body>
</html>
+1  A: 

Add a window.location = this.href; to your click function. That should work.

smack0007
A: 

So, you want to trigger click or simply relocate? Link is relocating by nature, but when you trigger onclick to other event it just performes binded function.

I'd propose you to break this task into following parts to keep your code cleaner: 1) separate function to perform needed actions, including using window.location.href="yournewurl" (or some advanced stuff with jquery plugin like this http://www.oakcitygraphics.com/jquery/jqURL/jqURLdemo.html). 2) call this function on needed events, say onclick etc.

Or just force location in if (event.keyCode == 13) { ... } block.

Sergii