Solved

input box scroll to end of value with javascript

Posted on 2008-06-10
4
2,754 Views
Last Modified: 2012-06-21
I have an html input box of type="text" that has a value assigned to it that exceeds the display width.  My goal is to have some javascript that can grab focus of the input box and scroll the cursor to the end of the input box value and allow the user to append to the current value.  I have used the following code to position the character at the end of the input box value and this seems to work ok in IE.  However, in FF and Safari, only the cursor moves to the specified location and the text inside the input box does not track to the new position.  Is there a way I can have the input box show the end of the string (similar to using the righ-arrow key on the keyboard to scroll to the end of the last character in the input box)?
function setCaretTo(pos) { 

	   var obj=document.getElementById('myInputBox');

    if(obj.createTextRange) { 

        /* Create a TextRange, set the internal pointer to

           a specified position and show the cursor at this

           position

        */ 

        var range = obj.createTextRange(); 

        range.move("character", pos); 

        range.select(); 

    } else if(obj.selectionStart) { 

        /* Gecko is a little bit shorter on that. Simply

           focus the element and set the selection to a

           specified position

        */ 

        obj.focus(); 

        obj.setSelectionRange(pos, pos); 

    } 

}

Open in new window

0
Comment
Question by:proee
  • 3
4 Comments
 
LVL 11

Accepted Solution

by:
JohnSixkiller earned 250 total points
ID: 21759723
Hi,

it seems like Gecko issue. Lets try a little trick. The INPUT scrolls to the end of line after any key is pressed. So simulating key press will help.

InitKeyEvent DOM documentation: http://developer.mozilla.org/en/docs/DOM:event.initKeyEvent
PS: 27 is escape key
function setCaretTo() {

    var obj=document.getElementById('myInputBox');

	var pos = obj.value.length;

	if(obj.createTextRange) {

        /* Create a TextRange, set the internal pointer to

           a specified position and show the cursor at this

           position

        */

        var range = obj.createTextRange();

        range.move("character", pos);

        range.select();

    } else if(obj.selectionStart != null) {

        /* Gecko is a little bit shorter on that. Simply

           focus the element and set the selection to a

           specified position

        */

        obj.focus();

        obj.setSelectionRange(pos, pos);
 

		var evt = document.createEvent("KeyboardEvent");

		evt.initKeyEvent(

                 "keypress",        //  in DOMString typeArg,

                  true,             //  in boolean canBubbleArg,

                  true,             //  in boolean cancelableArg,

                  null,             //  in nsIDOMAbstractView viewArg,  Specifies UIEvent.view. This value may be null.

                  false,            //  in boolean ctrlKeyArg,

                  false,            //  in boolean altKeyArg,

                  false,            //  in boolean shiftKeyArg,

                  false,            //  in boolean metaKeyArg,

                   27,               //  in unsigned long keyCodeArg,

                   0);              //  in unsigned long charCodeArg);

		obj.dispatchEvent(evt);

    }

}

Open in new window

0
 

Author Comment

by:proee
ID: 21762214
Ok, that's a great idea!  Here's the results from my testing.  It works in FF 2+, but throws the following error:

[Exception... "'Permission denied to set property XULElement.selectedIndex' when calling method: [nsIAutoCompletePopup::selectedIndex]" nsresult: "0x8057001e (NS_ERROR_XPC_JS_THREW_STRING)" location: "JS frame :: file:///I://junk.html :: setCaretTo :: line 84" data: no]
[Break on this error] obj.dispatchEvent(evt);

Any ideas on why this error is happening?

Also, in Safari for windows, it works but only after running the function two times.
Opera = does not work  (that's ok, but curious if initKeyEvent works for Opera).
0
 

Author Comment

by:proee
ID: 21765493
upon further research, it appears the above error is related to something in FF which is going to be fixed in version 3.  The only fix is a hack that is to put and autocomlete="off" inside the input tag.  This however, is not w3C compliant html code but prevent the javascript error.  Choose your poison!
0
 

Author Closing Comment

by:proee
ID: 31465951
Thanks a million.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now