Geeks With Blogs
Rajesh Pillai My experiments with asp.net mvc, jquery, wpf, silverlight, sharepoint, tdd and design patterns.

This edition of blog tip shows you how to focus a text input on a page to the desired element.

Use jsbin.com for executing/troubleshooting or just for learning jquery or any other popular js
framework that it supports.

I'll show two ways to do this based on the scenarios you encounter.

Using jQuery $(selector).focus method when the DOM is ready:

// When the HTML DOM is ready

$(function() {
     $("#elementId").focus();
});

The above works in most cases but may be annoying in situations you have a slow internet
connection and the cursor may be focussed than desire as the user may have already started
entering the desired input when the DOM loads and the cursor is reset again.

To avoid this put the script block immediately after the input tag where you wish to have focus on

<script type="text/javascript">
    $("elementId').focus();
</script>
 

 

 

Posted on Wednesday, November 25, 2009 3:32 PM jQuery | Back to top


Comments on this post: jQuery Receipe: Focussing a Text Input on Page

# re: jQuery Receipe: Focussing a Text Input on Page
Requesting Gravatar...
It's better if you use
$(document).ready(function(){
$("#elementId").focus();
});
Left by Đỗ Hồng Ngọc on Nov 30, 2009 10:11 AM

# re: jQuery Receipe: Focussing a Text Input on Page
Requesting Gravatar...

Its same as what I mentioned.
$(function() {
$("#elementId").focus();
});

The above one is the shortcut for $(document).ready(function () { ...});
Left by Rajesh Pillai on Nov 30, 2009 10:47 AM

Your comment:
 (will show your gravatar)


Copyright © Rajesh Pillai | Powered by: GeeksWithBlogs.net