Search code examples
javascripthtmlif-statementinnerhtml

Why does my javascript keep referring to the same innerHTML?


I'm building a voice assistant with javascript and html, and before I added the weather command (the last 'else if'), the code worked fine, but now, every time I try to ask the program something else, e.g. the date, the time, the innerHTML keeps displaying the weather. I've tried many different things but still with no avail. How come the innerHTML keeps displaying the weather instead of my other commands?

Here is my code, and since it requires mic access, here is the website: https://voice-assistant-development.stcollier.repl.co/. You can try it out yourself to see what I mean.

function record() {
 var recognition = new webkitSpeechRecognition();
 recognition.lang = "en-GB";
 recognition.start();
 recognition.onresult = function(event) {
   let transcript = event.results[0][0].transcript;
var str = transcript;
//Weather Code
var input = "Detroit";
var desc = document.querySelector('#output');


fetch('https://api.openweathermap.org/data/2.5/weather?q='+input+'&units=imperial&appid=6a3b95f23e761e707120f86b0eed7d55')
.then(response => response.json())
.then(data => {
  var tempValue = data['main']['temp'];
  var nameValue = data['name'];
  var descValue = data['weather'][0]['description'];
  var humidvalue=data['main']['humidity'];
  var mintemp=data['main']['temp_min'];
  var maxtemp=data['main']['temp_max'];
  var weather_now = "It's " + tempValue +" degrees Farenheight outsite currently, with a low of " +mintemp + " degrees Farenheight and a high of " + maxtemp + " degrees Farenheight. The humidity percentage for today is " + humidvalue + "%. The current weather is "  + descValue + ".";

  
desc.innerHTML = weather_now;

})
//End of Weather Code
//Date Code
const d = new Date();
var weekday = new Array(7);
  weekday[0] = "Sunday";
  weekday[1] = "Monday";
  weekday[2] = "Tuesday";
  weekday[3] = "Wednesday";
  weekday[4] = "Thursday";
  weekday[5] = "Friday";
  weekday[6] = "Saturday";
var wkday = weekday[d.getDay()];
const months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var msg_date = "It's " + wkday + ", " + months[d.getMonth()] + " " + d.getDate() + "th " + d.getFullYear() + "."
//End of Date
//Time Code
function formatAMPM(date) {
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'PM' : 'AM';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = "It's " + hours + ':' + minutes + ' ' + ampm;
  return strTime;
}
var msg_time = formatAMPM(new Date);
//End of Time
var msg_hello = ['Hello!', 'Hello, User!', 'Hi!', 'Hello! How are you doing?'];
var msg_notunderstood = ["I'm not sure what you mean.", "I don't understand. Maybe try rephrasing?", "I'm sorry, I don't understand. Please try again."]
var affirmative_msg = ['Here you go!', 'Sure thing!']
if (str.includes('hello')) {
 responsiveVoice.speak(msg_hello[Math.floor(Math.random()*msg_hello.length)], 'US English Female');
} else if (str.includes('date')) {
  document.getElementById('output').innerHTML = msg_date
  responsiveVoice.speak(msg_date, 'US English Female')
} else if (str.includes('time')) {
  document.getElementById('output').innerHTML = msg_time
  responsiveVoice.speak(msg_time, 'US English Female')
} else if (str.includes('email')) {
  window.open("mailto:")
} else if (str.includes('weather')) {
  document.getElementById('output').innerHTML = weather_now
  responsiveVoice.speak(weather_now, 'US English Female')
} else {
  document.getElementById('output').innerHTML = "I don't know what you mean."
  responsiveVoice.speak(msg_notunderstood[Math.floor(Math.random()*msg_notunderstood.length)], 'US English Female');
}
    document.getElementById('speechToText').value = event.results[0][0].transcript;
  }
}

//Mic Trigger Key
document.body.onkeyup = function(e){
    if(e.keyCode == 32){
      record()
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Document</title>
</head>
<body>
   <label for="Speech Recognition">Speech Recognition</label>
   <input type="text" name="" id="speechToText" placeholder="Speak Something" disabled="disabled" value="">
   <button onclick="record()">Record</button>
   <p id="output"></p>
      <h1 class="name" id="name"></h1>
      <p class="desc"></p>
   <script src="https://code.responsivevoice.org/responsivevoice.js?key=x9uXdCB8"></script>
   <script src="script.js"></script>
</body>
</html>

Thanks for any help. I really appreciate it.


Solution

  • The issue is that the weather-retrieving fetch is inside your record loop - without a conditional - so it executes every time. Because it takes a moment to get the results, it overrides any of your other outcomes. I would recommend putting it in another function and storing the variable so you can grab it when needed. If you put it in a window.onload event, it will fire when the page loads, so there won't be a delay when the voice command requests it.

    let weather_now
    
    window.onload = function() {
      fetch('https://api.openweathermap.org/data/2.5/weather?q=' + input + '&units=imperial&appid=6a3b95f23e761e707120f86b0eed7d55')
        .then(response => response.json())
        .then(data => {
          let tempValue = data['main']['temp'];
          let nameValue = data['name'];
          let descValue = data['weather'][0]['description'];
          let humidvalue = data['main']['humidity'];
          let mintemp = data['main']['temp_min'];
          let maxtemp = data['main']['temp_max'];
          weather_now = "It's " + tempValue + " degrees Farenheight outsite currently, with a low of " + mintemp + " degrees Farenheight and a high of " + maxtemp + " degrees Farenheight. The humidity percentage for today is " + humidvalue + "%. The current weather is " + descValue + ".";
        })
    }
    
    function record() {
      var recognition = new webkitSpeechRecognition();
      recognition.lang = "en-GB";
      recognition.start();
      recognition.onresult = function(event) {
        let transcript = event.results[0][0].transcript;
        var str = transcript;
        //Weather Code
        let input = "Detroit";
        let desc = document.querySelector('#output');
        //Date Code
        const d = new Date();
        let weekday = new Array(7);
        weekday[0] = "Sunday";
        weekday[1] = "Monday";
        weekday[2] = "Tuesday";
        weekday[3] = "Wednesday";
        weekday[4] = "Thursday";
        weekday[5] = "Friday";
        weekday[6] = "Saturday";
        let wkday = weekday[d.getDay()];
        const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
        var msg_date = "It's " + wkday + ", " + months[d.getMonth()] + " " + d.getDate() + "th " + d.getFullYear() + "."
        //End of Date    
        let msg_time = formatAMPM(new Date);
        //End of Time
        let msg_hello = ['Hello!', 'Hello, User!', 'Hi!', 'Hello! How are you doing?'];
        let msg_notunderstood = ["I'm not sure what you mean.", "I don't understand. Maybe try rephrasing?", "I'm sorry, I don't understand. Please try again."]
        let affirmative_msg = ['Here you go!', 'Sure thing!']
        if (str.includes('hello')) {
          responsiveVoice.speak(msg_hello[Math.floor(Math.random() * msg_hello.length)], 'US English Female');
        } else if (str.includes('date')) {
          document.getElementById('output').innerHTML = msg_date
          responsiveVoice.speak(msg_date, 'US English Female')
        } else if (str.includes('time')) {
          document.getElementById('output').innerHTML = msg_time
          responsiveVoice.speak(msg_time, 'US English Female')
        } else if (str.includes('email')) {
          window.open("mailto:")
        } else if (str.includes('weather')) {
          document.getElementById('output').innerHTML = weather_now
          responsiveVoice.speak(weather_now, 'US English Female')
        } else {
          document.getElementById('output').innerHTML = "I don't know what you mean."
          responsiveVoice.speak(msg_notunderstood[Math.floor(Math.random() * msg_notunderstood.length)], 'US English Female');
        }
        document.getElementById('speechToText').value = event.results[0][0].transcript;
      }
    }
    
    // Time 
    function formatAMPM(date) {
      let hours = date.getHours();
      let minutes = date.getMinutes();
      let ampm = hours >= 12 ? 'PM' : 'AM';
      hours = hours % 12;
      hours = hours ? hours : 12; // the hour '0' should be '12'
      minutes = minutes < 10 ? '0' + minutes : minutes;
      let strTime = "It's " + hours + ':' + minutes + ' ' + ampm;
      return strTime;
    }
    
    //Mic Trigger Key
    document.body.onkeyup = function(e) {
      if (e.keyCode == 32) {
        record()
      }
    }