Search code examples
javascripthtmlnode.jsartificial-intelligence

how to set an active listen function that wait and listens for a command from user


I was working on this javascript program that listens to the users command and replies correspondingly but currently, that listen() function is activated by a click of a button. What I'm trying to figure out is how can I set a function that constantly keeps listening for a command from the user like a certain word that then activates the listen() function. Ex. Alexa starts listening when her name is called. Current Code:

<button class="mdl-button mdl-js-button mdl-button--fab mdl-js-ripple-effect mdl-button--colored" onclick="listen()">

Solution

  • I would suggest having another onInput listener which will check whether a user has entered a certain word.

    Once that word is entered then invoke a function to add a listen() event listener to that button.

    eg: HTML -

    <input type="text" name="" id="userI">
    <button id="activate">Find Secret</button>
    

    JS -

    const btn = document.getElementById("activate");
    const input = document.getElementById("userI");
    
    
    input.addEventListener("input", (e) =>{
        if(input.value=="secret")
        {
            btn.addEventListener("click", secret);
        }
    })
    
    const secret = () => {
        alert("Secret is....");
    }
    

    This is just an idea. You can add many improvements. Like removing the event listener again. And so on.