Is there a way to dynamically incorporate line numbers into Google Code Prettify?

Having some trouble with formatting code and inserting/removing line numbers dynamically. The line numbers appear on the first page load, but disappear after clicking run. They don't show at all on my website. I want to allow users to click a button and toggle line numbers on/off:

<body>
  <pre id="pre">
    &lt;script type=&quot;text/javascript&quot;&gt;
    // Say hello world until the user starts questioning
    // the meaningfulness of their existence.
    function helloWorld(world) {
      for (var i = 42; --i &gt;= 0;) {
        alert('Hello ' + String(world));
      }
    }
    &lt;/script&gt;
    &lt;style&gt;
    p { color: pink }
    b { color: blue }
    u { color: &quot;umber&quot; }
    &lt;/style&gt;
</pre>


<button id="button">My button</button>
</body>

$(document).ready(function(){
  $("#button").on("click", function(){
         $("#pre").addClass("prettyprint").addClass("linenums").addClass("lang-js");
     $("#pre").html(PR.prettyPrintOne($("#pre").html()));
  });
});

Thanks!

EDIT: Line number issue different than How to add line numbers to all lines in Google Prettify?. Initially, line numbers show up when manually adding linenums class to pre tag. However, toggling them on/off with jquery doesn't work.

Answer №1

When you use the prettyPrintOne method, you are bypassing the class-based initialization process. This method takes arguments that dictate how prettify should behave.

Although you are attempting to alter how prettify behaves using classes, prettify disregards this because it only focuses on the arguments, which are null in this case and therefore revert to internal defaults.

The documentation for the method explains this:

    /**
     * Pretty print a chunk of code.
     * @param {string} sourceCodeHtml The HTML to pretty print.
     * @param {string} opt_langExtension The language name to use.
     *     Typically, a filename extension like 'cpp' or 'java'.
     * @param {number|boolean} opt_numberLines True to number lines,
     *     or the 1-indexed number of the first line in sourceCodeHtml.
     * @return {string} code as html, but prettier
     */

prettyPrintOne is used for parsing code passed as a string and returning the prettified result based on the arguments provided. On the other hand, prettyPrint scans the DOM for specified classes and executes accordingly. To achieve toggling, continue using prettyPrintOne to control when to display prettified output and when to show the original content - further details on this later.

Additionally, you're instructing prettify to format JS while your content actually contains HTML with JS in script tags and CSS in style tags. Therefore, you should specify HTML as the lang extension instead of JS.

To implement these changes, adjust your call as follows, ensuring to include the prettify class for proper application of the prettify theme CSS:

$("#pre").html( PR.prettyPrintOne($("#pre").html(), "html", true) )
    .addClass("prettyprint");

Result:

https://i.sstatic.net/KW114.png

For toggling functionality, modify the logic so that you store the original HTML upon prettifying and restore it when clicking the button:

  $("#button").on("click", function() {
    var $pre = $("#pre"); // Cache jquery object

    if (!$pre.hasClass("prettyprint")) {
      $pre.data("original-html", $pre.html()); // Store original HTML 
      
      $pre.html(PR.prettyPrintOne($pre.html(), "html", true))
        .addClass("prettyprint"); // Apply prettify
    } else {
      $pre.html($pre.data("original-html"))
        .removeClass("prettyprint"); // Restore original HTML
      
      $pre.data("original-html", null); // Clear cache for next usage
    }
  });

Here's a jsfiddle demonstrating the above: https://jsfiddle.net/joshdavenport/68thqus1/27/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to bring GIFs into NextJS

I am currently working on my portfolio website using Nextjs and I would like to incorporate gifs into the site. However, I have been struggling to figure out how to do so. Below is the code that I have been working with: https://i.stack.imgur.com/zjoiD.pn ...

Error: The MUI Popper Component constantly closes when re-rendering due to props issue

I have been exploring how to structure a component incorporating MUI's Popover component, especially when dealing with dynamic props being passed to a controlled Slider component inside the Popover as well as the anchor element being updated dynamical ...

The onblur function is not being triggered

Recently, I encountered an issue while trying to invoke a JavaScript function onblur of a field. The main problems I faced were: 1) The popup inside the function call was triggered automatically during page load. 2) When attempting to access the functio ...

Using Jquery and Ajax to add information to a database

One of the challenges I'm facing involves a page with three forms, each containing separate variables that need to be inserted into a MySQL database for viewing. My current script is working fine, even though I am aware that `mySql_` is deprecated but ...

Elements that do not change when hovered over and that intersect

In the provided example, I am attempting to decrease the opacity of non-hover elements on an HTML page. The code snippet below successfully reduces the opacity of non-overlapping elements. However, when there is a background element that overlaps and shou ...

"I am facing an issue where the button does not appear centered after using jQuery

I can't help but notice that when applying CSS directly, my buttons end up centered horizontally. Yet, when I insert the same code using append(), the buttons seem to align towards one side instead. Here is the HTML/CSS code snippet: <div style=" ...

Dispatching identification to controller after submission

I am encountering an issue with a page that contains the following code: <div class="col-sm-2 displaybutton"> <div data-point-to="displaysHeader"> @using (Html.BeginForm("Administration", "Home", FormMethod.Post)) ...

What are the downsides of using PHP redirects instead of JavaScript redirects, given that most large websites opt for the latter?

After closely examining the source codes of redirect pages on several major websites that redirect to their sponsors, I found an interesting pattern. Out of the five websites analyzed, four were using different Javascript redirects: <script type="text ...

Experience choppy scrolling in Internet Explorer

Check out my click and drag scrolling Image Viewer here. While it functions perfectly in Firefox and Chrome, Internet Explorer is giving me some trouble. The movement seems jerky, especially when scrolling diagonally. It's like the scroll is sluggish ...

How can I arrange selected options at the top in MUI autocomplete?

I am currently working with mui's useAutocomplete hook https://mui.com/material-ui/react-autocomplete/#useautocomplete Is there a way to programmatically sort options and place the selected option at the top using JavaScript sorting, without resorti ...

What changes do I need to make in order for this code to be compatible with Google Sites?

I am working on creating a random redirect button and need to modify the code below in two ways: <script> <!-- /* Random redirect button- From JavaScript Kit (http://javascriptkit.com) Hundreds of scripts available for free! Please keep this cred ...

Utilizing stored data to display multiple markers on Google Maps with Node, MongoDB, Express, and EJS

I've been working on a project that involves passing values from mongodb to the google maps script in order to display multiple markers. While I've been able to load the map successfully, I'm facing difficulties defining my customers and loo ...

The error message that keeps popping up - "jQuery is loading with dojoConfig, but $

Here is the configuration for dojoConfig: <script type="text/javascript"> dojoConfig = { async: true, parseOnLoad: false, packages: [ { name: 'jquery', location: '//ajax.googleapis.com ...

Invoke a PHP function by utilizing a JavaScript AJAX post call

I have been exploring various topics extensively, but I have not been able to find a solution. My objective is to create an HTML hyperlink that triggers a Javascript AJAX post request on a PHP page to execute a PHP function (potentially with any number of ...

Ensure that the date is valid using Joi without transforming it into UTC format

Is there a method to validate a date using @joi/date without converting it to UTC? I need to ensure the date is valid before storing it in the database. Here's what I've attempted: const Joi = require('joi').extend(require('@joi/ ...

The HTML footer designed with bootstrap is not behaving as expected. It is not staying fixed at the bottom of the page and is not displaying at full width despite my coding efforts

Working on a small Sinatra app with bootstrap for layout, I'm encountering some issues. The layout is not sticking to the bottom and not displaying at 100% width as intended. Additionally, the footer text is not centering even after applying the text ...

Angular - remove elements from an array within a directive when encountering a source error

If an image does not exist, I need to remove the item and push the next one inside ng-repeat. Currently, I am using a custom directive called "noImage". myApp.directive("noImage", function() { return { link: function(scope, element, attrs) { ...

The typical initial default argument to be passed to the function using fn.apply

Recently, I discovered the power of using fn.apply() in JavaScript to store function calls with all their arguments intact for future use. In my specific situation, I don't require the first argument, which is the context (this), and I want to find a ...

Firefox compatibility issue with Angular JS for downloading excel files

I've encountered an issue with my AngularJS code for downloading an Excel file. While it works smoothly in Chrome and Internet Explorer, it fails to function in Firefox. The server response isn't presenting any problems. Here's the code snip ...

Adjust the position of the content to the bottom for a form-group in Bootstrap v4

Currently, I am facing an issue where my label is overflowing and wrapping around the input field, causing it not to align at the bottom of the div. Is there a straightforward CSS solution for this problem? I have experimented with position relative/absol ...