Hyphens
by phloe
HTML
<input id="text" value="" />
<button id="soft" type="button">Insert soft hyphen</button>
<h1 id="headline"></h1>
JavaScript
var shy = "\u00AD";
text.onchange = set;
text.value = "hello, world" + shy + "dominator";
function set () {
headline.innerHTML = text.value.replace(/\\u00AD/g, "­");
}
set();
soft.onclick = insertSoftHyphen;
function insertSoftHyphen () {
var pos = doGetCaretPosition(text);
var value = text.value;
text.value = value.slice(0, pos) + shy + value.slice(pos);
set();
}
function doGetCaretPosition (oField) {
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus ();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange ();
// Move selection start to 0 position
oSel.moveStart ('character', -oField.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
iCaretPos = oField.selectionStart;
// Return results
return (iCaretPos);
}