0

I have making a chat application

let adUsername = null;

$(document).off('keyup', '#w-input-text');  
$(document).on('keyup', '#w-input-text', function(event) {
  if ($.inArray(event.keyCode, [9, 16, 17, 18]) !== -1) return;
  let inputValue = $(this).text();
  if (inputValue.length == 0) return;
  inputValue = getActiveWord();
  if (!inputValue.includes("@")) return;
  inputValue = inputValue.replace('@', '');
  if (inputValue.length > 0) {
    if (adUsername == inputValue) return;
    adUsername = inputValue;
    $.ajax({
      url: BASE_URL + 'user-list/' + adUsername,
              method: 'GET',
              dataType: 'json',
              success: function(response) {
                   // Clear the user list
        $('#userListOnAd').empty();
                   // Populate the user list with the retrieved data
        for (let i = 0; i < response.data.length; i++) {
          let name = response.data[i].name;
          let user_id = response.data[i].user_id;
          let listItem = $('<li>').text(name);
          listItem.on('click', function() {
            let selectedUsername = $(this).text();
            $('#userListOnAd').hide();
            let updatedText = getReplacedString(selectedUsername);
            $('#w-input-text').html(updatedText);
          });
          $('#userListOnAd').append(listItem);
        }
                   // Show the user list
        $('#userListOnAd').show();
      },
              error: function() {
                   // Handle the error case
                }
    });
  } else {
           // Hide the user list if the input does not match the pattern
    $('#userListOnAd').hide();
  }
});

  
function getActiveWord() {
       // debugger
  let text = $('#w-input-text').text();
       // let start_index = $('#w-input-text')[0].selectionStart;
       // let end_index = $('#w-input-text')[0].selectionEnd;
       // let editableDiv = document.querySelector('.note-editable');
       // please check as per the stackblitz demo I saw this as the classname for the editable content area
  let sel = window.getSelection();
  let range = sel.getRangeAt(0);
  let start_index = range.startOffset;
  let end_index = range.endOffset;
  let previous_space_index = text.lastIndexOf(" ", start_index - 1);
  let next_space_index = text.indexOf(" ", end_index);
  let begin = previous_space_index < 0 ? 0 : previous_space_index + 1;
  let end = next_space_index < 0 ? text.length : next_space_index;
  let between_spaces = text.substring(begin, end);
  return between_spaces;
}

  
function getReplacedString(selectedUsername) {
       // debugger
  let text = $('#w-input-text').text();
       // let start_index = $('#w-input-text')[0].selectionStart;
       // let end_index = $('#w-input-text')[0].selectionEnd;
  let sel = window.getSelection();
  let range = sel.getRangeAt(0);
  let start_index = range.startOffset;
  let end_index = range.endOffset;
  let previous_space_index = text.lastIndexOf(" ", start_index - 1);
  let next_space_index = text.indexOf(" ", end_index);
  let begin = previous_space_index < 0 ? 0 : previous_space_index + 1;
  let end = next_space_index < 0 ? text.length : next_space_index;
  let between_spaces = text.substring(begin, end);
       ////////// Replace the word using above index
  let originalString = text;
  let wordToReplace = between_spaces;
  let replacementWord = `<mention data-id="101">@${selectedUsername}</mention>`;
       // Find the index of the word to be replaced
  let startIndex = begin;  // originalString.indexOf(wordToReplace);
       // Check if the word is found in the string
  if (startIndex !== -1) {
           // Get the substring before the word
    let substringBefore = originalString.substring(0, startIndex);
           // Get the substring after the word
    let substringAfter = originalString.substring(startIndex + wordToReplace.length);
           // Construct the updated string with the replacement word
    let updatedString = substringBefore + replacementWord + " " + substringAfter;
    originalString = updatedString;
           // console.log(updatedString); // Output: "The quick brown cat jumps over the lazy dog"
  } else {
    console.log("Word not found in the string");
  }
       // console.log(between_spaces);
  return originalString;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="userListOnAd">
  <li>Durvash Nimje</li>
  <li>ABC Nimje</li>
  <li>XYZ Nimje</li>
  <li>PQR Nimje</li>
</ul>
<div id="w-input-text" contenteditable></div>

I have try with above code, but not done, please suggest me proper way

Shuo
  • 1,512
  • 1
  • 3
  • 13
  • Try with something easier first, then look how other people have built chat applications on Github - e.g. https://github.com/tegioz/chat or https://github.com/ngrt/simpleChatApp (there are hundreds) – IVO GELOV Jul 19 '23 at 08:50
  • thanks for suggesion @IVOGELOV, actually i have build chat app and work properly, just I want to do suggest user list on type @ in chat textbox, and after click on specific user, that user will be put in textbox where my cursor was point, but still my issue is my cursor point not getting properly after focus out from textbox – Durvash Nimje Jul 19 '23 at 09:52
  • You can listen for `blur` or `focusout` event on the textarea, remember the cursor position, and restore it after choosing the specific user. – IVO GELOV Jul 19 '23 at 14:36
  • Thanks to support, after some R&D, I got the answer from the below link: https://stackoverflow.com/questions/6157992/twitter-style-autocomplete-in-textarea – Durvash Nimje Jul 21 '23 at 05:02

0 Answers0