Nicoletta
Nicoletta

Reputation: 57

Hide/Show div p5.js

I am using the p5.js library, and I am working on a speech recognition - text to speech project. Kind of a chatbot. Input is voice input which becomes a string. I am outputting the result from a txt file, using a markov chain. Output is a string contained in a div.

My question is:

Is there a way to hide/show the div containing my input/output (.myMessage and .robotMessage) in intervals? I want the whole screen first showing only the input when I am talking, then input disappears and only output showing, then when the computer voice finishes speaking my input is shown in the screen and so on...

Here some parts of the code, let me know if it is clear enough.

//bot
function setup() {
  noCanvas();

   //reads and checks into the text file
   for (var j = 0; j < names.length; j++) {
    var txt = names[j];
    for (var i = 0; i <= txt.length - order; i++) {
      var gram = txt.substring(i, i + order);
      if (i == 0) {
        beginnings.push(gram);
      }

      if (!ngrams[gram]) {
        ngrams[gram] = [];
      }
      ngrams[gram].push(txt.charAt(i + order));
    }

  }

  //voice recognition
  let lang = 'en-US';
  let speechRec = new p5.SpeechRec(lang, gotSpeech);

  let continuous = true;
  let interim = false;
  speechRec.start(continuous, interim);

  //text-to-speach
  speech = new p5.Speech(); 
  speech.onLoad = voiceReady;

  function voiceReady() {
    console.log('voice ready');
  }

  //input-ouput
  function gotSpeech() {
    if (speechRec.resultValue) {
      var p = createP(speechRec.resultString);
      p.class('myMessage');
    }
     markovIt();
     chooseVoice(); 
     speech.speak(answer);

  }
}

and

function markovIt() {
  var currentGram = random(beginnings);
  var result = currentGram;


  for (var i = 0; i < 100; i++) {
    var possibilities = ngrams[currentGram];
    if (!possibilities) {
      break;
    }
    var next = random(possibilities);
    result += next;
    var len = result.length;
    currentGram = result.substring(len - order, len);
  }

  var answer = result;
  window.answer = answer;
  var p2 = createP(answer);
  p2.class('robotMessage');
}

how the HTML looks

<div class="container">
    <div class="myMessage"></div>
    <div class="robotMessage"></div>
</div>

Upvotes: 1

Views: 1055

Answers (1)

Rabbid76
Rabbid76

Reputation: 211166

Use select() to get a document element by its id, class, or tag name. e.g:

let my_div = select("myMessage");

Change the style of an element by style().

e.g hide:

my_div.style("display", "none");

e.g. show:

my_div.style("display", "block");

See also Toggle Hide and Show

Upvotes: 1

Related Questions