Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change font size dynamically on specific paragraph <p> elements?

The following JSFiddle splits texts into individual paragraph <p> boxes with a set text limit.


Is it possible to change the text size in the boxes according to the select option through contenteditable while still allowing to edit, removing the text limit and remaining the dynamic size property?

UPDATE 2: The boxes generated all need to be:

"equal the same height and width"

and change when the font is updated dynamically, needing to be consistent across all elements.


UPDATE 3: The last generated paragraph is not equal to the other paragraphs with border size height.


UPDATE 4: All paragraphs need to be generated equally with the height attribute auto. The problem with the current answers is the that the last generated paragraph border also needs to equal the same height as the previous height border as the other paragraphs, including when changing the font size.

Update 5 [image]: Example of Problem with last divided paragraph height and border not equal to others.

Example of Problem with last divided paragraph height not equal to others.

Link to Fiddle

If a new fiddle could be provided, it would be very much appreciated, as I am still new to coding. Thank You!

$(function() {
  $('select').on('change', function() {
    var targets = $('p'),
      property = this.dataset.property;
    targets.css(property, this.value);
  }).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);
  });
}

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;
}
#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 {
  padding: 1.2em .5em;
  margin: 1.4em 0;
  border: 1px dashed #aaa;
}
<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>
like image 925
Dave Avatar asked Feb 21 '16 06:02

Dave


People also ask

How do I change the font size in a paragraph dynamically?

First, we increment the clicks variable. Then we declare fontSize using a template literal which adds our new clicks count to the startingFontSize and "px" to get a string. Finally, the innerHTML value of the button element is updated. Then we update the fontStyle property for both elements.

How do you change the font of a specific paragraph?

To change the font size of particular paragraph, we can use ID and CLASS both methods of CSS defining. The property to define the font size if "font-size" and we can define the value either in pixels or in percentage.

How do I change font size in P tag?

To change the font size in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <p> tag, with the CSS property font-size.

How do you change the font size in a paragraph in HTML?

To change font size in HTML, use the CSS font-size property. Set it to the value you want and place it inside a style attribute. Then add this style attribute to an HTML element, like a paragraph, heading, button, or span tag.


2 Answers

You can inject a dynamic style element into the DOM and update it with the font size you're after. You could use an MV* framework to update its content.

$('#FontSize').change(function(){
    var fontsize = $(this).val();
    $('#style').remove(); //yes, there are better ways to update its content
    $('head').append('<style id="style">#content { font-size: '+fontsize + '}</style>');
});

Fiddled: https://jsfiddle.net/ovfiddle/m75gre8o/1/

like image 133
Oleg Avatar answered Oct 31 '22 05:10

Oleg


Try like this

<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" 
     onchange="$('#textarea1').css('font-size',this.value)">
        <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"> Test text
</textarea><br>
    <br>
    <button id="go">Divide Text into Paragraphs</button>
</div>
like image 23
Niklesh Raut Avatar answered Oct 31 '22 03:10

Niklesh Raut