Guest User

battleofthebits.org firki_preview.js improved

a guest
May 24th, 2022
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. $(document).ready(function() {
  2.     // cancel will either:
  3.     // 1. do nothing (was idle)
  4.     // 2. clear debounce timer (waiting for user to stop typing)
  5.     // 3. cancel POST to interpret (debounce timer triggered, i.e. kicked off POST after user stopped typing but user started typing again)
  6.     var cancel = function() {};
  7.     $(document).on('change keyup paste', 'textarea', function() {
  8.         // cancel whatever's going on whenever user does something
  9.         cancel();
  10.         var string = $(this).val();
  11.         var $this = $(this);
  12.         var firki_preview;
  13.         if (string.indexOf("'[") >= 0) {
  14.             // start debounce timer to wait for user to stop typing
  15.             var timeoutId = setTimeout(function() {
  16.                 var post = $.post('/api/v1/firki/interpret',
  17.                     { firki_string: string },
  18.                     function(data) {
  19.                         // interpret finished uninterrupted, put cancel back to do nothing (idle)
  20.                         cancel = function() {};
  21.                         var preview_box = $('div.firki_preview');
  22.                         // special case for multiple posts edit
  23.                         if (preview_box.length > 1) {
  24.                             preview_box = $('div.firki_preview', $this.parents('.post'));
  25.                         }
  26.                         if (preview_box.length) {
  27.                             preview_box.html(data[0]);
  28.                         }
  29.                         else {
  30.                             var preview_box = $('<div class="firki_preview inner">' + data + '</div><div class="hMiniSeperator"></div>');
  31.                             $this.after(preview_box);
  32.                         }
  33.                     }
  34.                 );
  35.                 // POST kicked off, make cancel abort the POST if user starts typing again before POST is finished
  36.                 cancel = function() {
  37.                     post.abort();
  38.                 };
  39.             }, 150); // <<< CHANGE 150 HERE TO YOUR LIKING
  40.             // make cancel abort the debounce timer if user is still typing before timer fires
  41.             cancel = function() {
  42.                 clearTimeout(timeoutId);
  43.             };
  44.         }
  45.     });
  46. });
  47.  
Advertisement
Add Comment
Please, Sign In to add comment