Reputation: 3339
I want a link to be clicked when a key is pressed, I cooked up this jQuery:
$('form#form1').bind("keypress", function(e){
if(e.keycode == 13 || e.keyChar == 13 || e.which == 13){
$('.LoginBoxButton a').click();
}
});
It doesn't work, and I've read the following explaining why:
It's important to remember that click() will not trigger the default behavior on a link, even if nothing else is preventing it. So you can't use click() by itself to simulate the user clicking on a link and being taken to another url.
But how DO you simulate the user clicking on a link and being taken to another url?
Upvotes: 2
Views: 3201
Reputation: 44376
First of all jQuery's Event.which normalizes event.keyCode
and event.charCode
- so you don't have to check keyCode
/charCode
.
Secondly decide whether you want to simulate user click on element or just redirect to other location, because there is a huge difference between one and the second. While the last one just redirect the first one first execute all connected mousedown
/mouseup
/click
(in given order) events. Also if click
event will return false
redirection should be blocked.
So the code for the first situation is already given, but here's the code for true simulation:
<a href="test.html">LsINK</a>
<span>ROBOT</span>
$("a").mousedown(function() { alert("mousedown"); })
.mouseup(function() { alert("mouseup"); })
.click(function() { alert("click"); return false; });
$("span").click(function() {
if (false !== $("a").mousedown().mouseup().triggerHandler("click")) {
alert("Redirect to: " + $("a").attr("href"));
//window.location.href = $("a").attr("href");
}
});
Upvotes: 1
Reputation: 5667
But how DO you simulate the user clicking on a link and being taken to another url?
These are two different things:
The first, simulate user clicking, is a quite low-level task. I'd choke to a browser that allowed it without limits.
The second, taking the user to another url, is as easy as assigning the url you want to document.location.href
.
So, instead of
$('.LoginBoxButton a').click();
use
document.location.href = $('.LoginBoxButton a').attr('href');
Hope this helps.
Upvotes: 2
Reputation: 382616
You may go about like this:
$('form#form1').bind("keypress", function(e){
if(e.keycode == 13 || e.keyChar == 13 || e.which == 13){
document.location.href = $('.LoginBoxButton a').attr('href');
}
});
Upvotes: 4