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);
var CaretPosition = GetCaretPosition(txtHyperLink);
var line = GetCurrentLine(txtHyperLink.value, CaretPosition);
if (line) {
line = line.trim();
if (line.length > 0) {
if (line.indexOf(‘:
line = "http://" + line;
}
OpenHyperLink(line);
}
}
}
function GetCaretPosition(control) {
var CaretPos = 0;
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)) {
if (Sel2.htmlText.substr(0, 2) == "\r\n") {
CaretPos += 2;
CharactersAdded = 2;
}
else {
CaretPos++;
CharactersAdded = 1;
}
Sel2.moveStart(‘character’);
}
CaretPos -= CharactersAdded;
}
else if (control.selectionStart || control.selectionStart == '0')
CaretPos = control.selectionStart;
return (CaretPos);
}
function GetCurrentLine(Text, Position) {
var lineTermination = "\n";
if (document.all) {
lineTermination = "\r\n";
}
var lineTerminationLength = lineTermination.length;
var startPosition = Position;
if (Position > 0)
Position–;
var lineStart = Text.lastIndexOf(lineTermination, Position);
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
- 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.
- The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.
CodeProject