Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 4830

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 27, 20242024-11-27T03:38:06+00:00 2024-11-27T03:38:06+00:00

Typewriter animation using Vanilla JS and Highlight.js

  • 61k

You’ve seen typewriter animations. You’ve seen the power of Highlight.js. Now you’re seeing the ultimate game-changer: typewriter animations for highlighted code, yay.

Typewriter Effect using Vanilla JS and Highlight.js

Most of the animations out there work only for a single line of text. Some even span multiple lines but only support a predefined text markup. Not ideal, let’s get started.

Highlight some code first

For demonstration purposes, we’re using code from the python requests library on GitHub.

<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> 
Enter fullscreen mode Exit fullscreen mode

Initialize the highlight.js library according to your project setup, following their usage guidelines. Then, highlight the code above:

<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> 
Enter fullscreen mode Exit fullscreen mode

At this point, we’re here (minus the container styling):

Code highlighted using the Darcula theme

Animate nodes, not individual characters

The struggle with animating code came from the fact that the various highlighters create their own markup. If we try to animate the text only, we get the desired typewriter effect, but we lose the highlighting. If we animate the whole HTML we may get highlighting, but this includes the markup itself, like, we’re printing <span class=> on the div.

So, we animate the nodes. It goes like this:

var children = Object.values(document.getElementById('code').childNodes);  target.innerText = '';  type(0); 
Enter fullscreen mode Exit fullscreen mode

Get all the child nodes of the highlighted code, empty the placeholder, and start displaying the nodes starting from the first one.

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)); } 
Enter fullscreen mode Exit fullscreen mode

And that’s it for the JS.

Bonus styling improvement

So far we’ve been working with this minimal CSS styling:

#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 */ } 
Enter fullscreen mode Exit fullscreen mode

Using various blinking cursors available online (couldn’t find the CodePen where I got it) we can add some extra styling.

#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;} } 
Enter fullscreen mode Exit fullscreen mode

Also, those scrollbars become pretty ugly. We don’t need them in our case so:

#code::-webkit-scrollbar {     display: none; } #code {     -ms-overflow-style: none;  /* IE and Edge */     scrollbar-width: none;  /* Firefox */ } 
Enter fullscreen mode Exit fullscreen mode

And that’s it, finally. Check it out on CodePen, and see it in action on my site.

csshighlightjsjavascriptwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.