Pages

Focusing on an element via anonymous function

Actually, the most challenging part of this post was the title. Defining its content in a few words was not so easy as writing it.

The problem is writing a piece of JavaScript code to set the focus on an element in the HTML page when the page is loaded. It is a pretty simple issue, but I felt it was worthy spending a few words.

Say that we want to put the focus on an element named "focusMe" when the page is loaded. This is the code that does the trick:

<script type="text/javascript">
window.onload = function () { document.getElementById('focusMe').focus(); }

// ...
</script>

The code included in the function body should be clear: we get the element with id "focusMe" and call focus() on it.

More interesting is how we assign it to the window onload property, the one responsible to keep the reference to the function that has to be called at page load time: we create a function with no name, and we include in its body the code we want to be called.

We could have given any name to this function, but why bother? the only caller of this piece of code already know where to find it, and no one else would need it.

No comments:

Post a Comment