Adjust the size of all automatically created paragraphs on the fly

Would it be possible to create a feature in the provided Fiddle that allows users to dynamically drag all generated paragraphs (<p> tags)? The text within each paragraph should still maintain its content attribute and flow properly into each paragraph when resizing.


Fiddle

$(function() {
  $('select').on('change', function() {
    //Lets target the parent element, instead of P. P will inherit it's font size (css)
    var targets = $('#content'),
      property = this.dataset.property;
    targets.css(property, this.value);
    sameheight('#content p');
  }).prop('selectedIndex', 0);
});
var btn = document.getElementById('go'),
  textarea = document.getElementById('textarea1'),
  content = document.getElementById('content'),
  chunkSize = 100;
btn.addEventListener('click', initialDistribute);
content.addEventListener('keyup', handleKey);
content.addEventListener('paste', handlePaste);

function initialDistribute() {
  var text = textarea.value;
  while (content.hasChildNodes()) {
    content.removeChild(content.lastChild);
  }
  rearrange(text);
}

function rearrange(text) {
  var chunks = splitText(text, false);
  chunks.forEach(function(str, idx) {
    para = document.createElement('P');
    para.setAttribute('contenteditable', true);
    para.textContent = str;
    content.appendChild(para);
  });
  sameheight('#content p');
}

function handleKey(e) {
  var para = e.target,
    position,
    key, fragment, overflow, remainingText;
  key = e.which || e.keyCode || 0;
  if (para.tagName != 'P') {
    return;
  }
  if (key != 13 && key != 8) {
    redistributeAuto(para);
    return;
  }
  position = window.getSelection().getRangeAt(0).startOffset;
  if (key == 13) {
    fragment = para.lastChild;
    overflow = fragment.textContent;
    fragment.parentNode.removeChild(fragment);
    remainingText = overflow + removeSiblings(para, false);
    rearrange(remainingText);
  }
  if (key == 8 && para.previousElementSibling && position == 0) {
    fragment = para.previousElementSibling;
    remainingText = removeSiblings(fragment, true);
    rearrange(remainingText);
  }
}

function handlePaste(e) {
  if (e.target.tagName != 'P') {
    return;
  }
  overflow = e.target.textContent + removeSiblings(fragment, true);
  rearrange(remainingText);
}

function redistributeAuto(para) {
  var text = para.textContent,
    fullText;
  if (text.length > chunkSize) {
    fullText = removeSiblings(para, true);
  }
  rearrange(fullText);
}

function removeSiblings(elem, includeCurrent) {
  var text = '',
    next;
  if (includeCurrent && !elem.previousElementSibling) {
    parent = elem.parentNode;
    text = parent.textContent;
    while (parent.hasChildNodes()) {
      parent.removeChild(parent.lastChild);
    }
  } else {
    elem = includeCurrent ? elem.previousElementSibling : elem;
    while (next = elem.nextSibling) {
      text += next.textContent;
      elem.parentNode.removeChild(next);
    }
  }
  return text;
}

function splitText(text, useRegex) {
  var chunks = [],
    i, textSize, boundary = 0;
  if (useRegex) {
    var regex = new RegExp('.{1,' + chunkSize + '}\\b', 'g');
    chunks = text.match(regex) || [];
  } else {
    for (i = 0, textSize = text.length; i < textSize; i = boundary) {
      boundary = i + chunkSize;
      if (boundary <= textSize && text.charAt(boundary) == ' ') {
        chunks.push(text.substring(i, boundary));
      } else {
        while (boundary <= textSize && text.charAt(boundary) != ' ') {
          boundary++;
        }
        chunks.push(text.substring(i, boundary));
      }
    }
  }
  return chunks;
}

 function sameheight(selector){
var max_y=0;
var y=0;
$(selector).css('height','');
$(selector).each(function(){
  y=$(this).outerHeight();
  if(y>max_y) max_y=y;
});
$(selector).css('height',max_y);
  }
#text_land {
  border: 1px solid #ccc;
  padding: 25px;
  margin-bottom: 30px;
}
textarea {
  width: 95%;
}
label {
  display: block;
  width: 50%;
  clear: both;
  margin: 0 0 .5em;
}
label select {
  width: 50%;
  float: right;
}
* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}
body {
  font-family: monospace;
  font-size: 1em;
}
h3 {
  margin: 1.2em 0;
}
div {
  margin: 1.2em;
}
textarea {
  width: 100%;
}
button {
  padding: .5em;
}
p {
 /*Here the sliles for OTHER paragraphs*/
}
#content p {
  font-size:inherit;/*So it gets the font size set on the #content div*/
  padding: 1.2em .5em;
  margin: 1.4em 0;
  border: 1px dashed #aaa;
  overflow:hidden;
}

p {width:400px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="styles">
  <label>Font-size:
    <select data-property="font-size">
      <option disabled>
        Select font-size:
      </option>
      <option>
        smaller
      </option>
      <option>
        10px
      </option>
      <option>
        12px
      </option>
      <option>
        14px
      </option>
      <option>
        16px
      </option>
      <option>
        18px
      </option>
      <option>
        20px
      </option>
      <option>
        larger
      </option>
    </select>
  </label>
</div>
<div>
  <h3>Paste text in the field below to divide text into paragraphs..</h3>
  <textarea id="textarea1" placeholder="Type text here, then press the button below." rows="5">
  </textarea>
  <br>
  <br>
  <button id="go">Divide Text into Paragraphs</button>
</div>
<div>
  <h3 align="right">Divided Text Will Appear Below:</h3>
  <hr>
  <div id="content"></div>
</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

sequenced pauses within a sequence of interconnected methods in a class

scenario: There are two javascript classes stored in separate files, each utilizing a different external service and being called within an express.js router. Refer to the "problematic code" section below: route routes.post('/aws', upload.sing ...

Could someone offer some assistance in grasping the order of operations in jQuery syntax

Until now, my approach has been deciphering and analyzing various codes and techniques for effectively utilizing jQuery, but I often find myself overwhelmed by the choices presented. This often leads to unnecessary complexity in my code. What I aim to ach ...

Why is my HTML5 class unable to locate the contents of my observable array?

Any help would be greatly appreciated. I've been coding for over fifty years, but I'm relatively new to JavaScript, HTML, and knockout. This project seems promising if I can just get it to function correctly. What follows is one of the many appro ...

Incorporate an array in PHP and employ jQuery's 'get' method

I am attempting to query the database in PHP and retrieve a "toplist" that is limited to 10 results. My goal is to create an array and send it back to Jquery using $.get(). However, I am facing issues with receiving all the data with this code. How can I ...

Tips on creating a recursive function based on depth levels

Function in need of completion: public static function f($rows) { $str = '<ul>'; $level = 1; foreach($rows as $row) { if($row['section_level'] > $level) ...

Regularly fetching images from PHP page

Recently, I encountered a challenge with a PHP page that retrieves arguments from the URL to generate an image. The image type (png, gif, etc.) is unknown. Typically, the page is used to embed the image in a standard HTML page like so: <img src="page.p ...

Introducing a fresh new feature incorporating various div elements through the power of JQuery

Why am I unable to retrieve the text of the newly added child divs? I am using JQuery to dynamically add these elements. Here is my sample fiddle: JSFIDDLE Could someone please guide me on what mistake I made? Javascript Code: var counter = 0; $("butto ...

The Skeleton-Avatar and ImageButton components in MUI React have had their backgrounds reshaped into perfect ovals

I am facing an issue with the mui Stack where all the background shapes of the Skeleton Avatar and background area are turning into oval or ellipsoid shapes. I have tried setting equal width and height for Avatar but it has not solved the problem. Is ther ...

Struggling with a Javascript problem where a button appears to be unresponsive when clicked. How can I fix this issue

I'm facing an issue with a web interface I am designing for configuring remotes to control ESP32 functions. The problem seems to be related to the Javascript part of the interface, as the code on the ESP32 is working fine. Here's how it works: th ...

Executing a function on a dynamically generated JavaScript button

Is there a way to create a button that triggers an onClick event calling a function with the signature deleteEntry(entry)? I'm encountering an error stating that entry is undefined even though I have used it in the same function. Adding escape charact ...

Implementation of Undo/Redo feature in an AngularJS CRUD application

We are exploring the idea of developing an AngularJS application similar to Excel that includes support for undo/redo functionality when editing cells. Do you have any suggestions on the most effective approach to implement this feature? I am not only in ...

JavaScript encountered an Uncaught TypeError when trying to read the property 'length' of an undefined value within an array

Currently, I am encountering an issue with passing arguments into a function. When I pass two arguments into the specified array setup and try to log them using console.log, an exception is thrown. Strangely, if I remove the arguments from the parameters ...

Having trouble downloading a PDF file on a local server with React and the anchor tag element

Having trouble downloading a pdf file from my react app to my Desktop. I've reached out for help with the details How to download pdf file with React. Received an answer, but still struggling to implement it. If anyone new could provide insight, that ...

What is the best way to combine and calculate elements in an array that is nested within an array using a specific condition or rule?

I have a JavaScript array of arrays with different data types that looks like this: let bigArray = [["A", "B", 221.67],["C", "B", 221.65],["B", "D", 183.33],["B", "A", 4900],[ ...

How can we utilize user input to query the API effectively?

Currently, I am utilizing the API to retrieve anime information. To fetch a specific anime, the endpoint is: https://nyaaapi.herokuapp.com/nyaa/anime?query={nameofanime} I am seeking to input the name of the anime from the user. Being new to APIs and J ...

Inquiries regarding the functionality of passport.js, particularly concerning the user.id implementation

In my model, doc, or record, there is no field labeled as id. So, how is it possible that done(null, user.id) works? I do have an _id but not an id. It seems like a passport object is being added to my session with the _id of the user in the database. But ...

Managing asynchronous requests with RxJS for time-spaced dependent API calls

I am currently working on developing a code in Angular 11 to handle the following scenario: I have a list of files, and for each file, I need to make an API call (let's say api1) to retrieve a fileId from the response. Subsequently, I will use this f ...

Press the button to execute a PHP script without redirecting the current page

Looking for a solution to make my webpage more user-friendly. I have a table generated from MySQL with buttons at the beginning of each row. When a user clicks on a button, I want the content of that specific row to be transferred to another MySQL table. ...

What could be the reason for meteor not injecting the text from my template helpers?

My goal is to dynamically generate a table displaying two different sets of data. Despite having verified returns from my database, the rendered page does not show the corresponding HTML elements as expected. Here is the template and HTML code: <templ ...

Ways to eliminate the space separating a parent div and a list within

Is there a way to eliminate the gap on the left that is causing the list to be separated from the div and have the list aligned with the left border? I attempted setting the li position to absolute and left:0px, but this resulted in overlap and loss of al ...