3

Why I am getting this error:

Uncaught RangeError: Maximum call stack size exceeded

Here is my code:

$(document).on('keypress focusout', '.checklist-item-input', function (e) {
  if (e.which == 13 || e.type == 'focusout') {
    $('.checklist-item').removeClass('edit');
    $(this).siblings('.checklist-item-detail').text($(this).val());
    $(this).blur();
    $('.checklist-item-detail').each(function () {
      if (!$(this).text().length) {
        $(this).closest('.checklist-item').parent().remove();
      }
    });
  }
});
maxshuty
  • 9,708
  • 13
  • 64
  • 77
mohamed youssouf
  • 1,485
  • 2
  • 11
  • 15
  • 5
    'Cause on `focusout` you call `.blur()` which raises `focusout` which calls `.blur()` which raises `focusout` which calls `.blur()` which raises `focusout` which calls `.blur()` which raises `focusout` which calls `.blur()` which raises `focusout` which calls `.blur()` .... etc – freedomn-m Nov 17 '16 at 15:26
  • 2
    `$(this).blur();` executes the focusout event, infinite times called – Kevin Kloet Nov 17 '16 at 15:26

1 Answers1

1

As others mentioned you effectively cause a recursive call. One simple fix is to add a sentinel variable to stop it going recursive:

var busy = false;
$(document).on('keypress focusout', '.checklist-item-input', function (e) {
  if (!busy && e.which == 13 || e.type == 'focusout') {
    busy = true;
    $('.checklist-item').removeClass('edit');
    $(this).siblings('.checklist-item-detail').text($(this).val());
    $(this).blur();
    $('.checklist-item-detail').each(function () {
      if (!$(this).text().length) {
        $(this).closest('.checklist-item').parent().remove();
      }
    });
    busy = false;
  }
});
iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202