How to make a typewriter animation using Vanilla JS and Highlight.js

Typewriter Effect using Vanilla JS and Highlight.js
<div id="code">
def get_encoding_from_headers(headers):
"""Returns encodings from given HTTP Header Dict.
:param headers: dictionary to extract encoding from.
:rtype: str
"""
content_type = headers.get('content-type') ...
</div>
<link rel="stylesheet"       href="//cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.0.1/build/styles/base16/darcula.min.css">
<script src="//cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.0.1/build/highlight.min.js"></script>
<script>var target = document.getElementById('code');hljs.highlightElement(target);</script>
Code highlighted using the Darcula theme
var children = Object.values(document.getElementById('code').childNodes);

target.innerText = '';

type(0);
function type(i) {
// Little helper
function randomNumber(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
// Make the content visible
if (i === 0) {
target.style.visibility = 'visible';
}
// When we've displayed all the nodes
// Just start over
if (i >= children.length) {
i = 0;
target.innerText = '';
}
// Append each node to the target code placeholder
// And scroll that div if the code scrolls past it
if (children.hasOwnProperty(i)) {
target.appendChild(children[i]);
target.scrollTop = target.scrollHeight;
}
// Step to the next node
i++;
// Repeat the process
// after a variable amount of time
setTimeout(function () {
type(i);
}, randomNumber(200, 500));
}
#code {
white-space: pre; /* So the code won't wrap */
width: 600px;
height: 300px;
margin-left: auto;
margin-right: auto;
overflow-x: auto; /* You know, so it doesn't overflow*/
overflow-y: auto;
visibility: hidden; /* The yet unhighlighted code better hide */
}
#code:after{
content: "|";
animation: blink 500ms linear infinite alternate;
}

@-webkit-keyframes blink{
0%{opacity: 0;}
100%{opacity: 1;}
}

@-moz-keyframes blink{
0%{opacity: 0;}
100%{opacity: 1;}
}

@keyframes blink{
0%{opacity: 0;}
100%{opacity: 1;}
}
#code::-webkit-scrollbar {
display: none;
}
#code {
-ms-overflow-style: none; /* IE and Edge */
scrollbar-width: none; /* Firefox */
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store