Keyup/input trigger only once

by lshettyl

HTML

<input id="myInput" type="text" />

JavaScript

/*
$(function() {
    $("input").on("keyup input", function(e) {
        
        //Capture the bound events
        var boundEvents = $._data($(this)[0], "events");
        
        if (
            'oninput' in document.createElement('input') &&
            boundEvents.hasOwnProperty("input") &&
            e.type === "keyup"
        ) {
            //When input is available, disable keyup as input will anyway fire!
            return;
        }
        $("#demo").append(e.type + "<br/>");
    });
});
*/

$(function() {
    $("#myInput").on("keyup input", function(e) {
        var $this = $(this),
            $lastState = $this.data('lastState') || '',//read back the element's previous state (or empty string if this is the first call)
            val = $this.val();//current state
        if(val !== $lastState) {//the all-important test.
            $this.data('lastState', val);//store current state to be read back at next call
            //here do whatever is required of your event handler.
        }
    });
});