Search code examples
jqueryevent-handlinginfinite-loopjquery-events

Why is only one of these (nearly) identical demos getting stuck in a loop?


I have been fighting with the weirdest loop. I simplified my code down to these two NEARLY IDENTICAL jsFiddles.

  1. http://jsfiddle.net/brentonstrine/crzTB/5/ (infinite loop)
  2. http://jsfiddle.net/brentonstrine/crzTB/7/ (runs as I expected)

One of them gets stuck in a loop (open your console). One of them does not.

The only difference is a class name. Seriously, open them in two tabs and go back and fourth. They're identical.

I've tested this in Chrome, Firefox and IE on multiple computers, varying which one I open first. Same result every time. Why??????????????

$("body").on("keydown", ".fixedValue:not(input)", function (e) {
    e.preventDefault();
    console.log("the div (which is not input?) was triggered.");

    $(".fixedValue input").trigger("keydown", e.keyCode);
});

$(".fixedValue input").on("keydown", function (e) {
    console.log("input (e.g. not the div) triggered.");
});

Solution

  • As JayC said, the reason the one doesn't recurse is because you didn't change all instances of the class name. To fix your actual problem, try this:

    $(".fixedValue input").on("keydown", function (e) {
        e.stopPropagation();
        console.log("input (e.g. not the div) triggered.");
    });
    

    See here.

    The keydown event was bubbling to the parent div and then getting triggered again on the child.