firebasefirebase-realtime-database

Firebase event "<user> is writing..." like WhatsApp


Is there any manner to clone the whatsapp event "[user] is writing..." in Firebase events?

I have reading about the Firebase events in https://www.firebase.com/docs/web/api/ but I've not found anything about the issue.

Thanks.


Solution

  • I wrote such a typing indicator a while ago.

    var ref = new Firebase('https://<your-app>.firebaseio.com');
    var input = document.getElementById('input');
    var typers = document.getElementById('typers');
    var uid = Date.now(); // generate a fake user id
    var timer;
    
    // attach a listener that display all people current typing in a list
    ref.on('value', function(snapshot) {
      typers.innerText = '';
      snapshot.forEach(function(typer) {
        var li = document.createElement('li');
        li.innerText = typer.key();
        typers.appendChild(li);
      });
    });
    
    // whenever the content of the textarea changes
    input.addEventListener('input',function(e) {
      // mark this user a "typing"
      ref.child(uid).set(true);
      // if we're counting down, stop the timer
      if (timer) clearTimeout(timer);
      // remove this user in 2 seconds
      timer = setTimeout(function() {
        ref.child(uid).remove();
      }, 2000);
    });
    

    To see it in action, have a look at this JSBin. The tweet where I announced it.