JSFiddle - React, Tailwind, and code Playground

by kristenconnal

JavaScript

/* hw4.js  */
/* Kristen Connal 2018 */

// Set up window.onload function
window.onload = function() {

  //Check for button click and run function when clicked
  var pgBtn = document.getElementById('divideTranscript');
  pgBtn.addEventListener('click', changeText);

  // Create function for button click
  function changeText() {
    // Pull div content
    var div = document.getElementById('transcriptText');
    var divText = div.textContent;

    // Divide the text into an array of words
    var divArray = divText.split(" ");
    divArray = divArray.filter(function(str) {
      return /\S/.test(str);
    });

    //Clear inner html of div
    div.innerHTML = "";

    // Iterate over array
    for (i = 0; i < divArray.length; i++) {

      // Build SPAN elements, along with attributes
      var span = document.createElement('span');
      var space = document.createTextNode(' ');
      span.textContent = divArray[i];
      space.textContent = " ";
      span.setAttribute("className", "word");
      span.setAttribute("id", "word" + i);

      // Add SPAN elements to the original DIV
      div.appendChild(span);
      div.appendChild(space);

      // Add event listener for mouseover - change background to yellow
      span.addEventListener('mouseover', function() {
        this.setAttribute("style", "background-color: #FFFF00;");
      }, false);

      //Add event listener for mouseout - change background back to white
      span.addEventListener('mouseout', function() {
        this.setAttribute("style", "background-color: #FFFFFF;");
      }, false);

      // Close the for loop, function, and window.onload            
    };

  }
};