This's my code for adding eventListener of google/code-prettify what I want to achieve is displaying the code as a code when the user insert his code in the textarea it should be working but for some reason it doesn't
<body onload="PR.prettyPrint()">
<h1>Insert your code</h1>
<form method="POST">
<pre class=" prettyprint"> <code class=" prettyprint"> <?php echo htmlspecialchars($str); ?> </code></pre>
<div class=" prettyprint"> <textarea id="testcode" class=" prettyprint" id="code"> </textarea></div>
<script lang="javascript">
document.getElementById("testcode").addEventListener('onkeyup', PR.prettyPrint, false);
document.getElementById("testcode").innerText = "echo";
</script>
<input type="submit"></input>
</form>
</body>
The textarea and an example of printed code using the lib.
Documentation Documentation If you are calling prettyPrint via an event handler, wrap it in a function. Instead of doing:
addEventListener('load', PR.prettyPrint, false);
wrap it in a closure like:
addEventListener('onkeyup', function(event) { PR.prettyPrint(); }, false);
I used a similar library that is much better.
and is named highlight.js
I highly suggest not using the google library because is an archived project
it may have a lot of bugs not fixed
✅ this code have only 5 lines of JS code!
GIF example code in javascript, but you can use PHP or any other language you want (just see the docs)
const inputArea = document.querySelector("textarea");
const outputArea = document.querySelector("pre code");
inputArea.addEventListener("input", () => {
outputArea.innerHTML = inputArea.value;
hljs.highlightElement(outputArea);
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.6.0/build/styles/default.min.css" />
<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.6.0/build/highlight.min.js"></script>
<form>
<textarea></textarea>
<pre><code class="language-javascript"></code></pre>
</form>
benefits:
<pre><code class="language-js">...</code></pre>
so see their docs on how to use it https://highlightjs.org/usage/