Elegance lies in simplicity
The other day, I was trying to pick up nuances of DOM manipulation in JavaScript. As an assignment for myself, I set myself the task of capturing the value of an input box immediately after the TAB key had been pressed. It should be simple even for a n00b like me, right? Bind a function to an
onkeyup
listener, check for the TAB keypress in the function and perform whatever tasks you need to perform. Something like:
var catchTabPress = function(e) {
var unicode=e.charCode? e.charCode : e.keyCode;
if (unicode == 9) {
// TAB key identified as pressed.
perform_task_logic_here(variables)
}
}
To my utter & complete frustration, the input value that got captured would always be “” – an empty string. I diligently inserted console.log() statements and checked the console for keycodes of the events being fired.
The first ‘AHA!’ moment
Since it was bound to an onkeyup
, and since I wasn’t preventing the default behavior, (I still needed the cursor to jump to the next input box, remember?) the TAB key would return the value of the next input box when onkeyup
was fired!
Super! So I changed onkeyup
to onkeydown
so that the event would fire when the TAB was pressed down, thus returning the value of the input box it was still in. For good measure, I made sure that the catchTabPress
function returned true
so that the TAB would still jump to the next input box. I reloaded the page, entered something in the input box and pressed TAB.
It worked!
Overjoyed, I entered something into the next input box. This time, however, I accidentally clicked the mouse outside the input box and that’s when it struck me.
The second ‘AHA!’ moment
What the hell was I doing? All I needed was to fire my task-logic when the focus shifted from the input box! I didn’t need to check specifically for a TAB keypress; I needed to check if the input box had lost focus, that’s all. A simple onblur
would achieve exactly what I was trying to do without any of the extra fluff that I was so busy generating.
<input type="text" onblur="perform_task_logic_here(variables)" />
Lesson learnt: If you are trying to do something that seems way too complicated and unnecessary, it probably is.Also, there is always a much, MUCH simpler way of doing it.
My over-enthusiastic-but-under-efficient n00bness often puts me to shame like that. :/