How can the text content within a tag be divided into multiple tags based on a specific maximum height for each tag?

If you have a block of HTML and you want to ensure that no single element exceeds a certain height, how would you go about splitting the element into multiple smaller elements? Keep in mind that the window width may affect this solution, so let's assume we are working with a narrow window where the element’s height is greater than the desired limit.

Begin With

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>

Finish With

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type</p>
<p>specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>

Answer №1

To tackle this issue using pagination, one approach is to simulate the pagination effect by adjusting the view of the element based on scroll offset.

Check out this link for an example: http://jsfiddle.net/Dr7Rv/

The code below essentially duplicates the original content as needed and shifts the view of each duplicate by scrolling. This allows you to manipulate and position separate elements according to your preferences. The code supports both pixel height and line count, with the latter typically providing a better visual appearance.

$.fn.createPagedClones = function(measure, type){
  /// set up variables
  var p = $(this), i = 0, c, t, h = p.innerHeight();
  /// handle conversion from lines to pixels
  ( type == 'lines' ) && ( measure *= parseFloat(p.css('line-height')) || 22 );
  /// create a reusable CSS object
  c = {"height": measure+"px", "overflow": "hidden"};
  /// iterate through divisions and create offset views
  do{
    /// clone the original and adjust the view by scrolling
    t = ( t ? p.clone().insertAfter(t) : p ).css(c).scrollTop(i);
    /// increment i
    i += measure;
    /// stop when completed
  }while( Math.round(i) < h );
}

$(function(){    
  //$('.target-p-tag').createPagedClones(50, 'px');
  $('.target-p-tag').createPagedClones(3, 'lines');
});

Theoretically, you could modify the code above so that it always operates on the original content, making the pagination system effectively scroll the content per page. However, this version grants you the flexibility to position each page individually. For instance, you could place them side by side, though this may appear odd if dealing with elements of varying sizes like images.

Answer №2

Just a rough draft to illustrate the idea:

Check it out here

If you plan on using HTML within, make sure to implement the correct logic for splitting chunks without breaking tags. Consider using domParser or an external library like DOMParser.

Answer №3

Perhaps this solution may not be the most optimal, but it appears to be effective:

let containerHeight = 100;

$("p").each(function() {
    let words = this.innerHTML.split(" "),
        $paragraph = $(this).empty();

    for (let i = 0; i < words.length; i++) {
        if ($paragraph.height() > containerHeight) {
            $paragraph = $paragraph.text(function(i, val) {
                return val.split(" ").slice(0, -2).join(" ");
            }).clone().empty().appendTo("div");
            i--;
        }
        $paragraph[0].innerHTML += words[i] + " ";
    }
});​

In this code snippet, the div serves as a container for the <p> element.

DEMO: http://jsfiddle.net/RubCq/

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

Checking for the existence of a Vue.js component

In the ready: method of the root instance, I have certain tasks to perform but only if some components are not present (not declared in the HTML). Is there a way to verify the existence of a component? ...

Creating labels dynamically with jQuery and HTML, then retrieving their text values through jQuery

During runtime, I am dynamically generating a label using jQuery with the following code: var value="Hello"; $("#ID_listOfTopics").append('<label id="ID_item">' + value + '</label><br /><hr />'); However, I&apo ...

The issue with mocking collections using JSON files in Backbone is that it is not properly triggering the success callbacks in

For my project, I am exploring the use of .json files to mock GET requests in a backbone collection. Here is an example of my sample file: [ { "id": '11111', "name": "Abdominal Discomfort", "favori ...

Utilizing JavaScript to employ the indexOf function on arrays in MongoDB

In my script, I have an array outside mongodb called title. The dataset in mongodb contains fields that I do not want to include (Dataset_1). I am using an indexOf function to match values and create a ranking. The structure of Dataset_1 is as follows: g ...

What is the best way to modify the inline style width of a table td from pixels to percentage in order to make it

<table> <tr style="height:15pt;"> <td style="width:229pt;border-style:solid;border-width:0pt;padding:3pt 9pt 3pt 0pt;" valign="bottom" bgcolor="#c0c0c0"><p style="font-family:Times New Roman, serif;font-size:10pt;font-style:norm ...

Transform PHP array into a properly structured array or object that can be easily used in JavaScript

My PHP code contains an array that looks like this: $variation = [ attribute_label => "Choose your Color", attribute_name => "pa_choose-your-color", variations => [ "819" => "Red", "820" => "Blue", ...

The value of type 'X' cannot be assigned to type 'Y' or 'undefined'

In my code, there is a component that requires a prop with an enum value: export enum AType { some = "SOME", word = "WORD", } const MyComponent = (arg: AType) => {} When I try calling this component like so: <MyComponent ar ...

How can you ensure that it selects a random number to retrieve items from an array?

I am experiencing an issue with some code I wrote. Instead of displaying a random object from the array as intended, it is showing the random number used to try and display an object. <html> <body> <h1>HTML random objects< ...

Retrieving the XML data from an uploaded file using PHP

How can I upload an XML file to my server and extract its content? Step 4: Writing each row from the XML file into a database. This is my current attempt: xml_import.php <?php if(isset($_POST["submit"])){ echo "Let's test"; $uploaddir ...

Tips for removing a section of HTML code within a PHP script

I attempted to remove a "Search" button located in the top left corner of a website. While searching for a solution, I stumbled upon a helpful tip at this link: Best way to find out which php file has generated an html line of code in WordPress Even afte ...

The background color of the Bootstrap 5 navbar remains static and does not transition when scrolling

I'm currently developing an Angular application using Bootstrap 5. One of the features I am working on is a transparent navbar that should change to a dark color when the page is scrolled. However, I seem to be encountering an issue where the navbar r ...

Errors related to missing RxJS operators are occurring in the browser, but are not showing up in Visual Studio

Recently, I encountered a peculiar problem with my Angular4 project, which is managed under Angular-CLI and utilizes the RxJS library. Upon updating the RxJS library to version 5.5.2, the project started experiencing issues with Observable operators. The s ...

How about trying out the magic of Bootstrap columns?

My issue pertains to bootstrap columns. Whenever I zoom in on the browser, the columns start overlapping and the text from col-md-7 ends up over the image. Does anyone know of a solution to this problem? <div class="row"> <div class="col-md-5 ...

Is there a way to identify the duplicates within an array of numbers and also determine how many times each number is repeated?

Is there a way to find duplicates in an array that appear two or more times? For example, if I have an array of strings like this: var arrStr = 'i do as as becasue i do as'; function CheckDuplicates(sentence) { let arr = sentence.split(" "); ...

aiming at another iframe using its unique identifier

I currently have three IFrames set up in my index.html <html> <head> <title>Frame</title> <style> .Top { float:both; width:99.7%; height:18%; } .menu { float:left; width:13%; height:82%; } .mai ...

Enhance your website with Bootstrap 5's responsive rounded corners feature

Utilizing Bootstrap 5.3.1, I have successfully implemented responsive borders using the Utility API. My CSS file includes classes such as .rounded-top-sm-4 and .rounded-end-sm-4. # utilities_custom.scss @import "bootstrap/functions"; @import &quo ...

What is the best method to replace the `click` event of an element selected using jQuery?

As I work on my program, I am attempting to alter the click event of a jQuery element. However, rather than modifying it as expected, it seems to be adding a new event each time. $myelem = $('.nav-item'); $myelem.click(function(){ console.lo ...

The art of linking subscriptions

Greetings! I am currently attempting to connect multiple subscriptions together. changeBranch() { const bottomSheetRef: MatBottomSheetRef = this.bottomSheet.open(CCSBranchComponent, { data: this.branches }); this.subscription.add(bottomSheetRef.instan ...

Using a promise inside an Angular custom filter

I am attempting to implement a filter that will provide either a success or error response from the ret() function. The current code is returning {}, which I believe is its promise. .filter('postcode', ['$cordovaSQLite', '$q' ...

Switch from using a button element for user input to using a text input field when

I am encountering a simple issue. I want to initiate an ajax call using the following button <input type="submit" value="My Button" id="get" /> The challenge is that I prefer not to use a button, but rather plain text for activation instead of a c ...