JSFiddle - React, Tailwind, and code Playground

by Narayan Prusty

HTML

<div style="padding: 0px; position: relative; color: white;">
    <div id="display_code" style="height: 200px; width: 200px; background-color: white; position: absolute; top: 0px; left: 0px; white-space: pre-wrap; overflow-y: scroll; overflow: scroll; word-wrap: break-word; color: red; background: transparent;">
    </div>
    <textarea id="code" class="code" style="overflow-y: scroll; overflow-x: hidden; height: 200px; width: 200px; resize: none; position: absolute; top: 0px; left: 0px; background: transparent;">
    </textarea>
</div>

CSS

#display_code, #code
{
    font-size: 14px;
    line-height: 18px;
    font-family:sans-serif;
    letter-spacing: normal;
    font-style: normal;
    padding: 0px !important;
    border: 0px !important;
    font-weight: 200;
    outline: 0px;
}

#code
{
    opacity: 1;
    color: rgba(0, 0, 0, 1);
}

JavaScript

$('.code:not(.focus)').keyup(function(){                 
    
    var value = $(this).val();
       
    //highlight the value variable then change the newline character
    value.replace(/\r?\n/g,'<br/>');
    document.getElementById("display_code").innerHTML = value;
    
    //now make sure the div and textarea has the same scroll position.
    
});

$('#code').on('scroll', function () {
    var x = $('#code').scrollTop();
    $('#display_code').scrollTop(x);
        
    console.log("Textarea: " +  $('#code').scrollTop());
    console.log("Div: " +  $('#display_code').scrollTop());
    
    });


$(document).delegate('#code', 'keydown', function(e) {
  var keyCode = e.keyCode || e.which;

  if (keyCode == 9) {
    e.preventDefault();
    var start = $(this).get(0).selectionStart;
    var end = $(this).get(0).selectionEnd;

    // set textarea value to: text before caret + tab + text after caret
    $(this).val($(this).val().substring(0, start)
                + "\t"
                + $(this).val().substring(end));

    // put caret at right position again
    $(this).get(0).selectionStart =
    $(this).get(0).selectionEnd = start + 1;
  }
});