views:

233

answers:

1

I have some input[type="text"] textboxes on my form that are sometimes not wide enough for the content that gets typed into them.

Currently, if a user types more text that fits (but is under maxlength), the textbox scrolls as you would expect. When they tab out of the textbox, the textbox stays scrolled to the "end" of what they typed.

I am trying to find a way to reset the textbox to the beginning when a user tabs out of the field.

I looked at the suggestion here:

http://stackoverflow.com/questions/512528/set-cursor-position-in-html-textbox

...but it does not work in an onblur event because the solution actually causes the textbox to get focus again briefly before bluring again which causes an infinite loop.

Before I give up, does anyone have any solution to resetting the cursor to the beginning of a textbox in an onblur event?

+2  A: 

In Internet Explorer, you can set the scrollLeft property. That doesn't work in Firefox, but if you reset the value to itself, the it will scroll back to the beginning. Apparently either method works in Chrome. I don't have any other browsers available to test at the moment.

$("input[type=text]").blur(function() {
    this.value = this.value; // Firefox
    this.scrollLeft = 0; // Internet Explorer
});

I used jQuery because that's what I'm used to, but you can adapt it to whatever framework/method you use for events.

Matthew Crumley