Implementing such functionality from scratch is not easy since there are a lot of programming languages and each language has a certain coding syntax. If you are using wordpress for your blog, then you can go with the Englighter wordpress plugin.
If you are not using wordpress and created your blog on your own by using some sort of framework such as React, Angular, or Vue, then I recommend you to go with third-party libraries such as Highlight JS. This library is extremely useful and easy to use.
This is not going to be a detailed overview of Highlight JS, so I recommend you to please visit its official website to learn more about it.
HTML & CSS
- We have 2 elements in the HTML file (
code). These two tags are required to make Highlight JS work.
codeelement has a
- The Highlight JS has different themes for code syntax highlighting. You can pick any theme of your choice from its official website and add it using the
linkelement. In our case, we are using the CDN link of monokai theme.
- We have added a minified version of Higlight JS using the
scripttag. We are using a CDN link here but you can also download it and host it locally on your server.
scripttag at the bottom.
The functionality of Highlight JS is exposed by the
hljs object and this object contains the
initHighlightingOnLoad() method. We need to call this method to initialize Highlight JS. This is all that is required for its basic functionality.
NOTE: At the time of this tutorial, we are using an old version (v9.16.10) of Highlight JS. If you are using latest version, then please use
highlightAll() method instead of