Fake Textbox with custom caret
HTML
Fake Textbox with custom caret, selection color, and focus effect
<div class="fakeTB"></div>
<hr>
<!-- set the initFocus style to initially focus -->
<div class="fakeTB initFocus"></div>
<hr>
<div class="fakeTB"></div>
<hr>
<div class="fakeTB"></div>
<br/>Written by <a href="http://www.hughanderson.com">Hugh Anderson</a>
CSS
.fakeTB {
font-family: courier;
font-size: 14px;
background: #45484d;
background: -moz-linear-gradient(top, #45484d 0%, #000000 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #45484d), color-stop(100%, #000000));
background: -webkit-linear-gradient(top, #45484d 0%, #000000 100%);
background: -o-linear-gradient(top, #45484d 0%, #000000 100%);
background: -ms-linear-gradient(top, #45484d 0%, #000000 100%);
background: linear-gradient(to bottom, #45484d 0%, #000000 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#45484d', endColorstr='#000000', GradientType=0);
color: #21f838;
padding:5px;
overflow: hidden;
white-space:nowrap;
height:14px;
border: 2px solid #222;
border-radius:8px;
width:20em;
}
.fakeTB.focused {
box-shadow: 0px 0px 6px rgba(0, 255, 100, 0.75);
}
.fakeTB .caret {
display:inline-block;
min-width:15px;
height:5px;
background: #21f838;
margin-bottom:-3px;
color:black;
}
.fakeTB .caret.selection {
background:#00ffff;
color:black;
}
input.fake {
position:absolute;
top:-10000px;
}
JavaScript
(function ($) {
// exist as a jquery plugin, so it can be reused
$.fn.fakeTextbox = function () {
return this.each(function () {
var $me = $(this),
cursorTimer,
$tb = $('<input type="text" class="fake" />');
if ($me.data('ftbftw')) {
console.log('already initialized');
return;
}
$me.data('ftbftw', 1);
$tb.insertAfter($me);
function appendCaret(toHere, position, selStart, selEnd) {
if (position === selStart) {
toHere += "<div class='caret'>";
}
if (position === selEnd) {
toHere += "</div>";
}
return toHere;
}
function syncTextbox() {
var tbVal = $tb.val();
var tbLen = tbVal.length;
var selStart = $tb.get(0).selectionStart;
var selEnd = $tb.get(0).selectionEnd;
var newOut = '';
for (var i = 0; i < tbLen; i++) {
newOut = appendCaret(newOut, i, selStart, selEnd);
newOut += tbVal[i];
}
$me.html(appendCaret(newOut, i, selStart, selEnd));
if (selStart != selEnd) {
$('.caret', $me).addClass('selection');
}
}
$me.click(function () {
$tb.focus();
});
$tb.bind("change keyup", syncTextbox)
.blur(function () {
clearInterval(cursorTimer);
cursorTimer = null;
var $cursor = $('.caret', $me);
$cursor.css({
visibility: 'visible'
});
$me.removeClass('focused');
}).focus(function () {
if (!cursorTimer) {
...