Introduce new material at the start of each line, akin to what ::before accomplishes for the initial line

I am currently working on customizing the appearance of my <code>/<pre> tags while ensuring that users can still easily highlight and copy the code.

The method I had in mind (shown below) only applies to the first line and doesn't repeat for subsequent lines.

I believe this could be achieved with JavaScript, but I'm unsure about the most efficient way to do so without excessive processing.

body {
  font-family: sans-serif;
}

code, pre {
  background: #e5f3ff;
}

code.styled,
pre.styled {
  display: block;
  padding: 8px;
  margin: 8px 0;
  overflow-x: auto;
}

code.styled::before,
pre.styled::before {
  content: "–";
  padding-right: 8px;
}
<p>This is an example of using <code>::before</code> to add content,<br>
and still being able to highlight/copy text without copying prefix.</p>
<pre class="styled">
adb wait-for-device
adb reboot-bootloader
fastboot devices
</pre>
<p>Note: You can copy the code without having to worry about the prefix.</p>

Is there a more effective approach to achieving a similar effect across all lines? I am specifically interested in a vanilla JavaScript solution if feasible.

Answer №1

Check out this neat solution using only javascript

var _pre = document.querySelector("pre.styled");
_pre.innerHTML="<span class='line'>"+(_pre.textContent.split("\n").filter(Boolean).join("</span>\n<span class='line'>"))+"</span>";
body {
  font-family: sans-serif;
}

code, pre {
  background: #e5f3ff;
}

code.styled,
pre.styled {
  display: block;
  padding: 8px;
  margin: 8px 0;
  overflow-x: auto;
}

code.styled .line::before,
pre.styled .line::before {
  content: "–";
  padding-right: 8px;
}
<p>This is an example of using <code>::before</code> to add content,<br>
and still being able to highlight/copy text without copying prefix.</p>
<pre class="styled">
adb wait-for-device
adb reboot-bootloader
fastboot devices
</pre>
<p>Note: You can copy the code without having to worry about the prefix.</p>

Here's how it works: By extracting the textContent from pre as a string, we are able to split the string into an array of lines, then filter out any empty lines before finally joining the lines back together by enclosing each in a span.

Answer №2

If you prefer not to enclose each line in its own tag, an alternative option is to utilize a background image technique akin to the one outlined in this response:

styling each line inside pre with css

UPDATE: included code snippet

body {
  font-family: sans-serif;
}

code, pre {
  background: #e5f3ff;
}

code.styled,
pre.styled {
  display:block;
  font:normal 12px/22px Monaco,Monospace !important;
  color:#000;
  background-color:#e5f3ff;
  background-image: radial-gradient(circle at 50%, #333 0%, #333 10%, #e5f3ff 20%);
  background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='22' height='22'><circle cx='11' cy='11' r='3' fill='green' stroke='black' stroke-weight='1' /></svg>");
  background-size: 22px 22px;
  background-repeat: repeat-y;
  padding:0em 20px;
  overflow:auto;
}
<pre class="styled">
adb wait-for-device
adb reboot-bootloader
fastboot devices
</pre>
<p>Note: You can copy the code without having to worry about the prefix.</p>

Answer №3

One way to achieve this effect is by using a simple JavaScript function to wrap each line of text with span elements and style them accordingly:

$('.text-block').each( function() {
  var lines = $(this).text().split('\n');
  $(this).html('');

  for(var i = 0; i < lines.length; i++) {
    $(this).append( $('<span>').html( lines[i] ) );
  }

  $(this).children('span').css('display', 'block');
})

You can then use CSS to further style the spans, such as adding a custom bullet before each line:

.text-block span::before {
  content: "-";
  padding-right: 8px;
}
.text-block span {
  display: block;
}

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

At what point is ng-if triggered?

I am currently in the process of developing functionality for buttons that open directives in modal windows. To keep things simple, I decided to use a modal container flagged with the versus directive: <div ng-if="vm.Modal.Modal1"> <directive-for ...

Find distinct elements in an array of objects

Imagine you have an array filled with different objects: var itemsArray = [ {name: "apple", color: "red", weight: "100g"}, {name: "banana", color: "yellow", weight: "120g"}, {name: "apple", color: "red", weight: "100g"}, {name: "banana", color: "y ...

Submit a POST request using CoffeeScript to get a string from the returned object

I am encountering a small issue. Whenever I execute myVar = $.post('/check_2/', JSON.stringify({"newname": window.NEWNAME,}), callback, 'json') The variable 'myVar' holds an object. When I use console.log myVar, the output i ...

Looking to transition from Node.js version v4.4.5 to v6.11.0 on your Windows system?

npm cache clean npm update -g I attempted upgrading using the provided commands, but unfortunately, the update did not go through as expected. Seeking advice for a successful update process. (Currently on Node.js 4.4.5 and aiming to upgrade to Node.js 6. ...

Trimming content within an editable div in JavaScript: A guide

I am working on an editable div feature where users can input text for comments. My goal is to eliminate any unnecessary spaces before and after the text. For example, if a user types: "&nbsp;&nbsp;Hello&nbsp;world&nbsp;&nbsp;&nbsp ...

What are the steps to create offline documentation for sails.js?

I am looking to integrate offline sails.js documentation into my system. You can find the official documentation for sails.js maintained at this Sails.js Documentation. According to their documentation, they use doc-templater for building the documentati ...

Is it possible for me to add some PHP code to the action of a form?

Within a foreach loop, I have the following code that lists unique codes as links: <a href="" class="charcoal_link" style="line-height: 20px;" onclick="showMessageArea(this); return false;" > <?php echo $uniqueCode1?><span class="pink_tex ...

Struggling with my jQuery Ajax call, need some help

I am attempting to create an ajax request that will update the content of my select element. Below is the code for my request : $(function() { $("#client").change(function() { type: 'GET', url: "jsonContacts. ...

What is the best way to display rows in alternating red and green colors?

Currently, I am implementing the react table in my React project. I found valuable resources on how to use it at these links: https://github.com/tannerlinsley/react-table/tree/v6#codesandbox-examples and also here: https://www.npmjs.com/package/react-tab ...

axios interceptor - delay the request until the cookie API call is completed, and proceed only after that

Struggling to make axios wait for an additional call in the interceptor to finish. Using NuxtJS as a frontend SPA with Laravel 8 API. After trying various approaches for about 4 days, none seem to be effective. TARGET Require axios REQUEST interceptor t ...

Tips for modifying the icon of a div with a click event using vanilla JavaScript

My goal is to create a functionality where clicking on a title will reveal content and change the icon next to the title. The concept is to have a plus sign initially, and upon clicking, the content becomes visible and the icon changes to a minus sign. C ...

Leverage the power of PHP files within your JavaScript code

I have a PHP file with some calculations that I want to integrate into another JavaScript file. How can I pass variables from JavaScript to perform calculations inside the PHP file? Here is my JavaScript code: $("#upload").on("click", function(){ var ...

Display the HTML content once the work with AJAX and jQuery has been successfully finished

Below are the codes that I have created to illustrate my question. It's not a complete set of code, just enough to explain my query. The process goes like this: HTML loads -> calls ajax -> gets JSON response -> appends table row with the JSO ...

Encountered a TypeError in React 16.7: The function (0, _react.useState) is not recognized

Error: TypeError: (0 , _react.useState) is not a function React versions currently being used: "react": "^16.7", "react-dom": "^16.7", File src/App.js: import {memo, useState} from 'react' export default memo(() => { useS ...

Organize chat messages based on date using JavaScript

I came across a similar query, but it didn't resolve my issue. Check this out: How can I group items in an array based on date? My goal is to organize these chat messages by date after fetching them from the database using AJAX. The console displays ...

Utilizing BootStrap 4 to ensure uniform image sizes within a row of columns

I'm facing a challenge in creating a row of 4 images that are responsive and uniform in size, despite being different dimensions (640x799, 640x479, ...). I've attempted to use columns and img-fluid to achieve this, but the shorter images do not f ...

Eliminate the jQuery AJAX timestamp from the URL parameters

Is there a way to eliminate the jQuery AJAX cache buster code (_=3452345235) from string URLs? While working on a global AJAX fail handler, I need to identify which URL failed. However, every time I locate the failed request's URL, the jQuery cache q ...

The functionality of CSS transform appears to be malfunctioning on Firefox browser

My website, located at , features a logo that is centered within a compressed header. I achieved the centering effect using the following CSS command: .html_header_top.html_logo_center .logo { transform: translate(-63%, -2%); } This setup works perfe ...

Problem with Express.js serving dynamically generated index.html page

Currently, I'm immersing myself in a practice project to grasp the concepts of express and webpack with react and react router. My goal is to make sure all server requests are directed to index.html to avoid encountering "Cannot GET" errors when navig ...

Learn how to dynamically insert an element into an angular scope using a click event

Currently, I am working on a function called onGroundUserClick within the Scope passedScope. The goal is to have a function triggered upon the completion of loading the iframe that will establish ng-click. var $tdName = $("<td/>", { ...