Enclose every line within a span tag

I'm currently exploring ways to wrap each line of content in a span. For example, suppose I have an element structured like this:

.body-copy {
  position: relative;
  width: 100%;
  height: auto
}
<div class="body-copy">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est labour.
</div>

In order for the text to span the width of its container, I am seeking a way to enclose each line of content in a span upon document load, window load, and window resize. I wonder if this is even feasible? Your valuable suggestions on this matter would be highly appreciated!

Answer №1

If you're looking for a messy yet effective method to achieve your goal, here's an approach you can try. This method involves using a hidden div to compare the width with the original text as we gradually add words one by one. Once the width limit is reached, a new span element is created to hold the collected words. This process is repeated until all words are grouped into their respective span elements. The remaining words are then placed in their own span, and the original text is replaced with the updated HTML code. You can trigger the wordWrap() function whenever the document is loaded or the window is resized. To make it easier to visualize where the markup is applied, borders have been added to the span elements.

$(document).ready(function() {
  wordWrap();
});

function wordWrap() {
  var bdy = $(".body-copy");
  var text = $(bdy).text();
  var html = $(bdy).html();
  var bWidth = $(bdy).width();
  var words = text.split(" ");
  var span = "";
  var word = "";
  var allSpans = "";
  var lastWord = "";
  $(words).each(function(i, w) {
    if (lastWord != "") {
      w = lastWord + " "+ w ;
      lastWord = "";
    };
    word = w + " ";
    span = span + word;
    $(".body-copy-two").append(word);
    if ($(".body-copy-two").width() >= bWidth) {
      var wLen = word.length;
      span = span.slice(0, -wLen);
      lastWord = w + " ";
      allSpans = allSpans + "<span>" + $.trim(span) + "</span>";
      $(".body-copy-two").html("");
      span = "";
      word = "";
    }
  });
  var lastSpan = "<span>" + $(".body-copy-two").text() + "</span>";
  $(bdy).html(allSpans + lastSpan);
}
.body-copy {
  position: relative;
  width: 100%;
  height: auto
}

.body-copy-two {
  position: absolute;
  visibility: hidden;
}

.body-copy span {
  border: 1px solid black;
  display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="body-copy">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est labour.
</div>
<div class="body-copy-two"></div>

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

Having difficulty maintaining trailing zeroes in decimals after converting to float in Angular

I need assistance with converting a string to float in Angular. Whenever I use parseFloat, it seems to remove the zeros from the decimal values. How can I ensure that these zeros are retained with the numerical values? The example below should provide more ...

What is the correct way to assign a property to a function's scope?

Lately, I've been delving into Typescript Decorators to address a specific issue in my application. Using a JS bridge to communicate TS code between Android and iOS, we currently define functions as follows: index.js import foo from './bar' ...

Exploring the power of directives in AngularJS for dynamically manipulating the

Using angular directives, I am attempting to dynamically replace a portion of HTML within a portlet on a webpage. The portlet contains two embedded sections. The top section includes a heading obtained from a separate backend service. <div class="head ...

Transmit information to Flask server using an AJAX POST call

I'm completely new to Ajax requests. I'm trying to send data from a webpage to my Flask backend using an Ajax request, but I can't get anything to show up in the backend: Here is the request code I am using: function confirm() { cons ...

The console does not display the JSON data for requests and responses

I have successfully set up a server inside of VSCode, but unfortunately the request and response logs that I usually see in my terminal when running the server with npm start are not appearing. I would really like for them to display in the Debug Terminal ...

Verify the content of each file in a bulk upload before transferring them to the server

I am facing an issue with a form that has 3 separate file input fields. I need to validate their MIME types individually before uploading them to the server. The first two should only allow MP3 files, while the last one should only allow JPEG files. Is th ...

Show custom exception messages for jQuery Ajax error handling

Is there a way to display custom exception messages as alerts in jQuery AJAX error messages? For instance, if I trigger an exception on the server side using Struts with throw new ApplicationException("User name already exists");, how can I capture and di ...

Transforming HTML produced by an outdated ASP system to generate modern ASP.NET 2.0 web pages

I have a friend who is currently working on developing a solution to convert aspx pages from html pages generated by an older asp application. The plan involves running the legacy app, capturing the html output, cleaning the html with a tool like HtmlTidy ...

Tips for effectively utilizing foreach loops in JQuery

I've encountered an issue while displaying a list of data in a table using Smarty templates and foreach loops. I'm trying to make each line clickable to show new data below it, but currently, this functionality only works for the first line. Is t ...

I am currently using jQuery autocomplete in an attempt to display the value in the textbox as a table. The data is not being retrieved from a JSON source using Ajax directly in the text

Attempting ajax with json for autocomplete using Jquery for the first time, aiming for auto-complete appearance but table-like structure. Below is the jquery code snippet: $("document").ready(function (){ $(function () { $.ajax({ url: "dum ...

Customizable initiation time for the JQuery Countdown timer

I am in need of a customizable timer feature for my website that allows users to input their desired countdown duration in minutes and seconds. Additionally, having a start/stop function would be ideal. I have looked around for a suitable solution, but mo ...

Having trouble with Electron nodeIntegration functionality and experiencing some odd behavior in general with Electron

Having just started working with Electron, I find myself encountering some puzzling behavior that has me stumped. Here's a quick summary of the issue: I am unable to establish communication between Electron and the HTML "Uncaught ReferenceError ...

Tips for creating brief animations

I am currently working with a moving div in JavaScript that continues to move for a period of time after the key is released. I am looking for a way to immediately stop the animation upon releasing the key. The animation is controlled by a switch statemen ...

Prevent jQuery UI default styling from being applied

I'm curious about how to prevent jQuery UI from adding any classes when initializing $.tabs(). This is the structure of my HTML: <link href="smoothness/jquery-ui-1.8.20.custom.css" rel="stylesheet" type="text/css" /> ... <link href="estilos ...

Markdown in Vue.js filters

I found a helpful example by Evan You on how to convert HTML to markdown - check it out here. However, when trying to install the marked package via npm and implementing it, I encountered an error stating that 'marked' is not defined. After inc ...

What is the best way to display a multi-state component that includes an API fetch?

Currently, my tech stack includes React and Node.js. Within my project, I have a component named ItemList. This particular component fetches data from an API in the componentDidMount() method to facilitate rendering a "loading state." My objective is to ...

At what point is the JavaScript function expression triggered in this code snippet?

let express = require('express') let app = express(); app.use(express.static('static')); let server = app.listen(3000, function() { let port = server.address().port; console.log("The server has started on port", port); }); I ...

Using a PHP variable as the input for the img src attribute in HTML

I am currently working on a project that involves creating a gallery to showcase all the .jpg files from a specific local directory. However, I seem to be encountering some issues with it. <?php $directory = "img/"; $images = glob ...

Choosing a BeautifulSoup tag according to attribute value

Imagine we have an HTML page with an index and some content below. Each element in the index is linked to a related section in the document. Let's say our starting point is an anchor tag with an href value of "#001". We want to search through all the ...

Is there a way to retrieve two separate route details using jQuery simultaneously?

Clicking the checkbox should display the Full Name: input type="text" id="demonum" size="05"> <button type="button" onclick="load_doc()">click</button><br><br> <input type="checkbox" id ="check" > The r ...