Click here to Skip to main content
Click here to Skip to main content

JavaScript: How to Simulate Hyperlink editable list box with TextArea

By , 9 Jul 2010
 

This article intends to identify a technique to convert textarea HTML control to Editable Hyperlink Listbox efficiently.

Logic

The code snippet uses pure HTML and JavaScript technology.

Step 1: Bind TextArea “Double Click” event to the required JavaScript code.
Step 2: Get Caret/Cursor position within the text area.
Step 3: Extract current line text from text area.
Step 4: Check for valid URL format and fix URL if necessary.
Step 5: Open New window/Tab with selected URL.

Getting Caret/Cursor Position

The code for getting Caret/Cursor position is based on the Mr. Alex's implementation available at http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea.

However, the bug fix to count 2 characters for the IE line termination(“\r\n”) is included in this code.

Getting Current Selected Line

GetCurrentLine function uses string search functions to identify the line termination characters related to cursor position within the textarea to extract the selected line.

Code

String.prototype.trim = function() {      
    return this.replace(/^\s+|\s+$/g, "");       
}  

function OpenLink(hyperLinkID) {      
    var txtHyperLink = document.getElementById(hyperLinkID); 

    //Step 2: Get Caret/Cursor position with in the text area      
    var CaretPosition = GetCaretPosition(txtHyperLink); 

    //Step 3: Extract current line text from text area.      
    var line = GetCurrentLine(txtHyperLink.value, CaretPosition); 

    //Step 4: Check for valid URL format and fix URL if necessary      
    if (line) {       
        line = line.trim();       
        if (line.length > 0) {       
            if (line.indexOf(‘://’) == -1) {       
                line = "http://" + line;       
            } 

            //Step 5: Open New window/Tab with selected URL.      
            OpenHyperLink(line);       
        }       
    }       
} 

function GetCaretPosition(control) {      
    var CaretPos = 0;       
    // IE Support       
    if (document.selection) {       
        control.focus();       
        var Sel = document.selection.createRange();       
        var Sel2 = Sel.duplicate();       
        Sel2.moveToElementText(control);       
        var CaretPos = 0;       
        var CharactersAdded = 1;       
        while (Sel2.inRange(Sel)) {       
            //old GetCaretPosition always counts 1 for linetermination       
            //fixed       
            if (Sel2.htmlText.substr(0, 2) == "\r\n") {       
                CaretPos += 2;       
                CharactersAdded = 2;       
            }       
            else {       
                CaretPos++;       
                CharactersAdded = 1;       
            }                    
            Sel2.moveStart(‘character’);       
        }       
        CaretPos -= CharactersAdded;       
    }       
    // Firefox support       
    else if (control.selectionStart || control.selectionStart == '0')       
        CaretPos = control.selectionStart;      
    return (CaretPos);  
}  

function GetCurrentLine(Text, Position) {      
    var lineTermination = "\n"; //Mozilla opera etc       
    if (document.all) { // IE       
        lineTermination = "\r\n";       
    }       
    var lineTerminationLength = lineTermination.length;       
    var startPosition = Position;       
    //always search one character position back to avoid wrong calculations       
    //when cursor position is at the end of the line       
    if (Position > 0)       
        Position–;
    var lineStart = Text.lastIndexOf(lineTermination, Position);      
    //if cursor at first line or  new line and cursor at the beginning       
    if (lineStart == -1 || (lineStart <= 0 && startPosition == 0))       
        lineStart = 0;       
    else       
        lineStart = lineStart + lineTerminationLength;  
    var lineEnd = Text.indexOf(lineTermination, lineStart);      
    if (lineEnd == -1)       
        lineEnd = Text.length;       
    return Text.substring(lineStart, lineEnd);       
} 

function OpenHyperLink(line) {      
    window.open(line);       
} 

Disclaimer

  1. All data and information provided on this page is for informational purposes only. Some parts of this tutorial are taken from the specified links and references. The mentioned writings belong to their corresponding authors.
  2. The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.

Share/Bookmark

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Sabarinathan Arthanari
Technical Lead Mahindra Satyam
India India
Member
I have been programming for last 10 years on various platforms including .NET, Visual Basic 6, Oracle and SQL server.
 
I decided to write articles when I have free time hoping to share my thoughts with you.
 
To know more about me visit http://sabarinathanarthanari.com

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralFormat CodememberArun Jacob8 Jul '10 - 2:52 
GeneralRe: Format CodememberSabarinathan Arthanari8 Jul '10 - 8:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130513.1 | Last Updated 10 Jul 2010
Article Copyright 2010 by Sabarinathan Arthanari
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid