script.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Author: Matthew Shiel
  2. $("#user-input-form").submit(
  3. function (event) {
  4. event.preventDefault();
  5. // Store input in a variable
  6. var question = $('#user-input').val().trim() // Remove whitespace
  7. var bot = $('#bot-name').val().trim() // Remove whitespace
  8. var session = $('#session-id').val().trim() // Remove whitespace
  9. var user = $('#user-name').val().trim() // Remove whitespace
  10. // Clear the input box
  11. $('#user-input').val("");
  12. // If the user doesn't input anything return nothing
  13. if (!question) {
  14. return;
  15. }
  16. // Append the user's question to the list and clear input
  17. $("#output-area").append('<li>' + question + '</li>');
  18. // scroll to the bottom of the messages
  19. // adapted from https://stackoverflow.com/questions/11715646/scroll-automatically-to-the-bottom-of-the-page
  20. $('#output-area').animate({
  21. scrollTop: $('#output-area').prop("scrollHeight")
  22. }, 300);
  23. $.get('/user-input', {
  24. value: question,
  25. bot: bot,
  26. session: session,
  27. user: user
  28. })
  29. .done(function (data) {
  30. // Set a timeout to make Eliza seem like she's thinking
  31. // Adapted random number in a range from here https://stackoverflow.com/questions/1527803/generating-random-whole-numbers-in-javascript-in-a-specific-range
  32. setTimeout(() => {
  33. // Add Eliza's answer to the list
  34. addListItem(data);
  35. }, Math.floor(Math.random() * (2000 - 600 + 1)) + 600);
  36. })
  37. });
  38. function addListItem(input) {
  39. // Add the input to the list
  40. $("#output-area").append('<li>' + input + '</li>')
  41. // Automatically scroll to the last message
  42. // adapted from https://stackoverflow.com/questions/11715646/scroll-automatically-to-the-bottom-of-the-page
  43. $('#output-area').animate({
  44. scrollTop: $('#output-area').prop("scrollHeight")
  45. }, 300);
  46. }