Simtwo Simtwo - 7 months ago 20
Javascript Question

Define a width for each words and compose a title automatically

I’m searching for a way of automatically
compose a sentence using javascript.


Here is an example using this sentence :

«here is an amazing sentence well composed»
enter image description here
Then I’d like the block size to change dependind
on the word width
Different sizes
So that finally, it could look like this :Final result
So far, I only found how to cut the sentences in words.

How could I define a width for each «words / text block»
depending on their width ?



function wordsinblocks() {
var str = document.getElementById("demo").innerHTML;
var res = str.split(" ");
document.getElementById("demo").innerHTML = res;
}

body{
font-family:"helvetica";
font-size: 40px;
}
p {border: 1px solid black;}

<button onclick="wordsinblocks();">Design the sentence</button>
<p id="demo">Here is an amazing sentence well composed</p>




Answer

Before you put your words back in html, wrap each word into a span and style the spans. This is just the part of how would you design the spans. Based on letter count you could add grid classes to them.

Please note that i didn't write the styles for the grid classes, therefore that won't be visible.

function wordsinblocks() {
    var str = document.getElementById("demo").innerHTML;
    var res = str.split(" ");

    for (var x in res) {
      var l = res[x].length;
      var className = "grid-1";

      switch(true) {
          case (l < 3):
             className = "grid-1";
          break;
          case (l > 2 && l < 5):
             className = "grid-2";
          break;
          // and so on until you get all cases you wish to cover
          default: // and finally longer words would have the widest column class
             className = "grid-4";
          break;
      }

      res[x] = '<span class="word-item ' + className + '">' + res[x] + '</span>';
    }

    document.getElementById("demo").innerHTML = res.join(""); 
}
 body{
    font-family:"helvetica";
    font-size: 40px;
    }
p span.word-item {border: 1px solid black; padding: 0 0.5em; box-sizing: border-box; display: inline-block;}
<button onclick="wordsinblocks();">Design the sentence</button>
<p id="demo">Here is an amazing sentence well composed</p>

Comments