Automatic page element focus in MVC

It’s really annoying when a web page doesn’t have focus set to an element on the page by default. Especially for things you visit regularly like login pages. It shows no effort went into the design or UX.  So here’s a nice little trick to automatically set focus to the first textbox element on every page in your MVC site. Just add the following block of javascript to the HTML header section of the _Layout.cshtml, or whatever your chosen MVC 3 layout file is (in MVC 2, this will be the view master ASPX file).

<script type=”text/javascript”>
$(function () {
$(“input[type=text]”).first().focus();
});
</script>

This short but effective piece of jQuery script is executed every time a page loads, selects all text input elements and sets focus to the first one it finds.

Advertisements

About Phil Munro

I have been developing commercial desktop and distributed web applications with Microsoft technologies since 1997.
This entry was posted in ASP.NET MVC, Javascript, jQuery. Bookmark the permalink.