Search code examples
jqueryhtmlparentchatbot

jQuery chatbot insertAfter parent div


I have the following HTML

<div class="msg_box">
<div class="msg_head">
Jarvis
<div class="close">
  x
</div>
</div>
<div class="msg_wrap">
<div class="msg_body">
<div class="msg_insert"></div>
</div>
<div class="msg_footer">
<div class="input-group">
<input id="speech" type="text" class="form-control msg_input" 
placeholder="Type a message...">
<button id="rec" class="btn fa fa-microphone btn-custom" aria-hidden="true">
</button>
</div>
</div>
</div>
</div>

I want the chat bubbles to show after the user has typed a message

This is the jQuery i have

  var accessToken = "7f109c1f355c4e62815409938d71594f",
  baseUrl = "https://api.api.ai/v1/",
  $speechInput,
  $recBtn,
  recognition,
  messageRecording = "Recording...",
  messageCouldntHear = "I couldn't hear you, could you say that again?",
  messageInternalError = "Oh no, there has been an internal server error",
  messageSorry = "I'm sorry, I don't have the answer to that yet.";
  $(document).ready(function() {
  $speechInput = $("#speech");
  $recBtn = $("#rec");
  $speechInput.keypress(function(event) {
    if (event.which == 13) {
      event.preventDefault();
      var printmsg = $(this).val();
      send();
      $("<div class='msg_b'>" + printmsg + "
  </div>").insertBefore('.msg_insert');
    }
  });
  $recBtn.on("click", function(event) {
    switchRecognition();
  });
  $(".debug__btn").on("click", function() {
    $(this).next().toggleClass("is-active");
    return false;
  });
  });

  function startRecognition() {
  recognition = new webkitSpeechRecognition();
  recognition.continuous = false;
  recognition.interimResults = false;
  recognition.onstart = function(event) {
    respond(messageRecording);
    updateRec();
  };
  recognition.onresult = function(event) {
    recognition.onend = null;

    var text = "";
    for (var i = event.resultIndex; i < event.results.length; ++i) {
      text += event.results[i][0].transcript;
    }
    setInput(text);
    stopRecognition();
  };
  recognition.onend = function() {
    respond(messageCouldntHear);
    stopRecognition();
  };
  recognition.lang = "es-ES";
  recognition.start();
  }

  function stopRecognition() {
  if (recognition) {
    recognition.stop();
    recognition = null;
  }
  updateRec();
  }

  function switchRecognition() {
  if (recognition) {
    stopRecognition();
  } else {
    startRecognition();
  }
  }

  function setInput(text) {
  $speechInput.val(text);
  send();
  }

  function updateRec() {
  $recBtn.text(recognition ? "Stop" : "Speak");
  }

  function send() {
  var text = $speechInput.val();
  $.ajax({
    type: "POST",
    url: baseUrl + "query",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    headers: {
      "Authorization": "Bearer " + accessToken
    },
    data: JSON.stringify({
      query: text,
      lang: "en",
      sessionId: "yaydevdiner"
    }),
    success: function(data) {
      prepareResponse(data);
    },
    error: function() {
      respond(messageInternalError);
    }
  });
  }

  function prepareResponse(val) {
  var debugJSON = JSON.stringify(val, undefined, 2),
    spokenResponse = val.result.speech;
  respond(spokenResponse);
  debugRespond(debugJSON);
  }

 function debugRespond(val) {
  $("#response").text(val);
 }

function respond(val) {
  if (val == "") {
    val = messageSorry;
  }
  if (val !== messageRecording) {
    var msg = new SpeechSynthesisUtterance();
    msg.text = val;
    window.speechSynthesis.speak(msg);

  }
  var jarvis = msg.text;
  $("<div class='msg_a'>" + jarvis + "</div>").appendTo('.msg_insert');
  $('#speech').val('');
  $('.msg_body').scrollTop($('.msg_body')[0].scrollHeight);
}

The problem is that it does not add to the parent div and I can't seem to figure out why.

JSFiddle here


Solution

  • I don't know why you used a .msg_insert div for the "system" replies...

    But if you simple append messages, the user and the system ones...
    It behaves as expected.

    So I just changed two lines... One in the keypress handler:

    $speechInput = $("#speech");
    $recBtn = $("#rec");
    $speechInput.keypress(function(event) {
      if (event.which == 13) {
        event.preventDefault();
        var printmsg = $(this).val();
        send();
        //$("<div class='msg_b'>" + printmsg + "</div>").insertBefore('.msg_insert');
        $(".msg_body").append("<div class='msg_b'>" + printmsg + "</div>");
      }
    });
    

    And one in the respond function:

    function respond(val) {
      if (val == "") {
        val = messageSorry;
      }
      if (val !== messageRecording) {
        var msg = new SpeechSynthesisUtterance();
        msg.text = val;
        window.speechSynthesis.speak(msg);
    
      }
      var jarvis = msg.text;
      //$("<div class='msg_a'>" + jarvis + "</div>").appendTo('.msg_insert');
      $(".msg_body").append("<div class='msg_a'>" + jarvis + "</div>");
      $('#speech').val('');
      $('.msg_body').scrollTop($('.msg_body')[0].scrollHeight);
    }
    

    Updated Fiddle