Javascript blunders

I'am in need of help with strange behavior. There is peace of javascript:

    var timer;

    $("#dmn2, #dmn1, #tld").bind("keyup change", function () {
        clearTimeout(timer);
        timer = setTimeout(validateDomain, 2500);
        return false;
    });

It works when I type something in input field or select some option.

Now, the problem is when I enter something and click mouse away from input field. It registers double call. Seems clicking mouse away from input field counts as "change". How to prevent this?

Comments

  • The recommended way to get help with these things is to provide a jsfiddle with a minimal example of the issue described.

  • As @stevewatson301 said, a jsfiddle to better understand what you are trying to achieve would be good.
    But I took a shot and maybe what you are searching for is actually listening to a single "input" event?
    $('#on').on('input', function() { console.log('Even handler fired: on()'); });
    Try my example: https://jsfiddle.net/qLw2hym9/3/

    And maybe consider using "on()", as "bind()" is already considered deprecated.

  • edited June 7

    RTFM

    Depending on the kind of element being changed and the way the user interacts with the element, the change event fires at a different moment:

    • When the element loses focus after its value was changed, but not committed (e.g., after editing the value of or ).

    Also

  • A less pretty way of doing it would be to have a variable that saves the previous text, and when func fires it compares if the new text is different from the previous text. If so, it runs the code and updates the previous text variable with the new text, if not it just doesnt do anything. This way even if it double fires, it'll only run the code once.

    Thanked by (1)legendary
  • Here is relevant jsfiddle: https://jsfiddle.net/hmz5cd1b/# . Run it and bring up the console (beta), it will show error like this:

    "145:13 Uncaught ReferenceError: request is not defined"

    ignore it, just take it as a request fact. Now click mouse away from input field, you will see duplicate request.

Sign In or Register to comment.