Javascript

[Javascript] textarea code highlighter effects

chsr 2022. 3. 14. 14:06
728x90
반응형

■ Javascript textarea code highlighter effects


■ 사용법

  • 라이브러리 선언
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.1.0/highlight.min.js"></script>

 

  •  CSS
@import url("https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.1.0/styles/github.min.css");
@import url('https://fonts.googleapis.com/css2?family=Nanum+Gothic+Coding:wght@400;700&family=Noto+Sans+KR:wght@100;300;400;500;700;900&display=swap');

/* code highlight css */
#editor-container { position: relative; min-height:50px; max-height:500px; overflow:auto; }
#editor-container #s_script, #highlighting-code { position: absolute; top: 0; left: 0; margin: 0; }
#editor-container #s_script, #highlighting-code { padding: 5px; font-family: 'Nanum Gothic Coding', monospace; font-size: 12px; line-height: 15px; }
#editor-container #s_script { color: transparent; background-color: transparent; z-index: 1; caret-color: red; min-height:50px; 
    border: 1px solid #ddd; border-radius: 3px; width:100%; }
#highlighting-code { z-index: 0; background:unset; border:0; }
#highlighting-code code { font-family: 'Nanum Gothic Coding', monospace; }

 

  •  HTML & Javascript
<div id="editor-container">
    <textarea id="s_script" name="s_script" placeholder="설치 스크립트 입력해주시기 바랍니다." spellcheck="false" oninput="update_code(); resize();" onkeydown="if(event.keyCode===9){var v=this.value,s=this.selectionStart,e=this.selectionEnd;this.value=v.substring(0, s)+'\t'+v.substring(e);this.selectionStart=this.selectionEnd=s+1;return false;}"></textarea>
    <pre id="highlighting-code" class="hljs"><code></code></pre>
</div>

<script type="text/javascript">
    function update_code() {
        const result_elem = document.querySelector("#highlighting-code code");
        const text = document.querySelector("#s_script").value;
        let html = hljs.highlightAuto(text).value;
        result_elem.innerHTML =  html.replace(new RegExp("  ", "g"), "&nbsp; ");;
    }

    function resize() {
        const editor = document.querySelector('#s_script');
        editor.style.height = "20px";
        editor.style.height = (editor.scrollHeight + 5)+"px";

        const editor_div = document.querySelector('#editor-container');
        editor_div.style.height = (editor.scrollHeight + 5)+"px";
    }

    document.addEventListener("DOMContentLoaded", () => {
        update_code();
        resize();
    });
</script>
728x90
반응형