Reputation: 2737
I'm new to JavaScript, and was wondering if there is a way to check where the focus was before the user pressed the Enter button. I want to process things differently based on the focus. Any ideas?
Upvotes: 2
Views: 232
Reputation: 1931
I guess that based on the focus means that if the user presses enter on an input you want to do one thing, and if the user presses enter into another input do something else.
if I am right, you don't have to check where the focus was. You want to bind functions to the onkeypress event.
<script>
function doStuffOnEnter()
{
var x = event.keyCode;
if(x == 13) // if user pressed intro
{
//do stuff
}
}
</script>
<input type="text" onkeypress="doStuffOnEnter()" />
the above code its very basic, but it's only for you to get the idea.
more info here: http://www.w3schools.com/jsref/event_onkeypress.asp
Upvotes: 3
Reputation: 166
If your site makes use of jQuery, which is common for those new to JavaScript, then you can store the DOMElement in a global variable for you to check.
var currentFocus = null;
$('input, textarea').focus(function() {
currentFocus = this;
});
This will allow you to know where the user last was "focused" when he pressed enter. If you're not using jQuery, the code would be a little longer but the same idea.
Upvotes: 2