Search code examples
javascriptjqueryrandomtypographyitalic

Randomly pick words in a page and turn them into italics on JS button click


I'd like to create a javascript button that, when clicked on, italicizes randomly a bunch of words -- say 200 -- in a text. It means that only certain words should be in italics, but each time different ones (regardless of their function or nature -- verb, noun, subjet, preposition etc).

I was thinking of calling an array and then get "str.italics()", but that would mean that I'll have to methodically copy into the code all the words of that text, right ? Plus it seems to be non standard. I'm sure there's a prettier way to do that.

Thanks.


Solution

  • This will randomly add italics to words in a div. It uses a randomized array of 0 to [word count] numbers to determine which words should be italicized in the main text.

    Adjust numWordsToItalicize to change the number of words italics are applied to.

    Fiddle

    Javascript

    var words = $('#words');
    var initialText = words.html();
    
    function italics(){  
      var wordArr = initialText.split(' ');  
      var randomArray = getRandomArray(wordArr.length);
      numWordsToItalicize = 100; 
    
      for(var i = 0; i < numWordsToItalicize && i < wordArr.length; i++) {
        wordArr[randomArray[i]] = '<span class="italic">' + wordArr[randomArray[i]] + '</span>';    
      }  
      words.html(wordArr.join(' '));
    }
    
    function getRandomArray(length) {
      var arr = [];
      for(var i = 0; i < length; i++) { arr.push(i); }
      return shuffleArray(arr);
    }
    
    function shuffleArray(array) {
      for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
      }
      return array;
    }
    
    $('#doItalics').on('click', function(){
      italics();
    });
    

    HTML

    <input id="doItalics" type="button" value="Italicize!" />
    <div id="words">
      A large amount of text...
    </div>
    

    CSS

    .italic {
      font-style: italic;
    }