jQuery Change Persister for DOM text inputs

/*
 jQuery tbChangePersister v1.0.0 - April 2015
 by Nick Kewney
 */
(function ($) {
    $.fn.tbChangePersister = function (next, defaultDelay, domStorageSuffix) {
        return this.each(function () {
            var timer = 0,
                that = $(this),
                delay = defaultDelay || 5000;
            that.keyup(function () {
                clearTimeout(timer);
                var context = that.val();
                if (localStorage) {
                    localStorage.setItem("tbChangePersisterValue-" + domStorageSuffix, context);
                }
                timer = setTimeout(function() {
                    next();
                }, delay);
            });
        });
    };
})(jQuery);

Example usage:

$("#myElement").tbChangePersister(function () {
            var d = new Date();
            var time = d.toLocaleTimeString();
            $("#myElementMessage").text("Draft autosaved " + time);
        }, 500, "myStorageName");

Set the value:

if (localStorage) {
            var content = localStorage.getItem("myStorageName");
            if (content) {
                $("#myElement").text(content);
            }
        }

 

Leave a Reply