Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cursor in transparent textarea

I wrote a small jQuery-plugin to highlight different parts in a textarea.

I added a <pre> behind the textarea which displays the code highlighted, the textarea is transparent:

HTML:

<textarea class="edit" rows="10"></textarea>

CSS:

pre {
    position: absolute;
    z-index: -1;

    outline: 1px dashed red;
}

.edit {
    outline: 1px dotted blue;
    opacity: 1;
    width: 50%;

    color: #000;
    border: 0px solid transparent;
    background: transparent;

    resize: vertical;
}

pre, .edit {
    overflow: auto;
    margin: 0;
    padding: 0;

    tab-size: 4;
    -o-tab-size: 4;
    -moz-tab-size: 4;

    line-height: 17px;
    font-family: monospace; 
    font-size: 13px;
}

JS:

$(document).ready(function() {
    $('.edit').after('<pre></pre>');

    var $code = $('pre');
    var position = $('.edit').position();

    $code.css('left', position.left + 'px');
    $code.css('top', position.top + 'px');
    $code.css('width', $('.edit').innerWidth() + 'px');
    $code.css('height', $('.edit').innerHeight() + 'px');

    $('.edit').on('input', function() {
         $('pre').html($(this).val());   
    });
});

Here is a preview: http://jsfiddle.net/Recode/HaPAe/

If I change the color of the text in the textarea to transparent, the cursor also disappears, because in Firefox (and some other browsers) it has always the same color as the text.

I found this snippet:

.edit { cursor: url(cursor.cur), default; }

But this changes only the mouse-cursor and not the one that says where I am in my text.

Is there a way to have a visible cursor although the text is transparent?

like image 420
kelunik Avatar asked Oct 15 '25 13:10

kelunik


1 Answers

The problem you're having happens because the colour of the insertion cursor is the same as the color of the text.

WebKit-only Solution

In WebKit browsers you can get around this by using the -webkit-text-fill-color property and setting that to transparent whilst still using a solid color:

.edit {
    color:#000;
    -webkit-text-fill-color:transparent;
}

Here is a JSFiddle example where I've set the color to #f00 - you can see the red insertion cursor, but you can't see the textarea text.

Unfortunately this will not work on Firefox or other non-WebKit browsers.

Non-WebKit Solution

Depending on what level of browser support you're going for, you can always drop the textarea completely and set the pre to contenteditable. jQuery's on('input'...) event handler will still trigger when applied to pre elements.

<pre contenteditable></pre>
$('pre').on('input', function() { ... });

JSFiddle example.

Do note though that with this you may need to strip formatting.

like image 137
James Donnelly Avatar answered Oct 19 '25 15:10

James Donnelly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!