jquery.clearable.js 2.83 KB
(function($) {
    var dom = '<i class="clearable"></i>';
    var Clearable = function(element, options) {
        var defaults = {
            // width: 16,
            // height: 16
        };
        var setting = this.setting = $.extend({}, defaults, options);
        var toggleFlag = false;
        // var callback = this.setting.callback;

        /*function toggle() {
            $dom.toggle();
            toggleFlag = !toggleFlag;
            if (typeof(callback) != "undefined") {
                callback();
            }
        }*/

        function toggle(targetFlag) {
            if (targetFlag === true) {
                $dom.show();
            } else if (targetFlag === false) {
                $dom.hide();
            } else {
                $dom.toggle();
                targetFlag = !toggleFlag;
            }

            toggleFlag = targetFlag;
            if (toggleFlag) {                
                update_location();
                $element.addClass('clearable-fixed');
            } else {
                $element.removeClass('clearable-fixed');
            }

        }


        var $element = $(element).on('keyup.clearable focus.clearable paste.clearable', function() {
            var self = this;
            setTimeout(function() {
                if (!!$(self).val().trim() !== toggleFlag) {
                    toggle();
                }
            }, 0);
        }).on('blur.clearable', function(e) {
            setTimeout(function() {
                toggle(false);
            }, 0);
        });

        var $dom = $(dom).on('click.clearable', function() {
                $element.val('');
                toggle();
            }).insertAfter($element);

        var p, height, mt, ml, width;
        function update_location() {
            p = $element.position();
            // if (!setting.width) {
                setting.width = $dom.outerWidth();
                setting.height = $dom.outerHeight();
            // }
            width = $element.outerWidth();
            height = $element.outerHeight();
            mt = parseFloat($element.css('margin-top'));
            ml = parseFloat($element.css('margin-left'));
            $dom.css({
                left: p.left + width + ml - setting.width + 'px',
                top: p.top + mt + (height - setting.height) / 2 + 'px'
            });
        }
        update_location();

        this.init();

    };

    Clearable.prototype = {
        init: function() {}
    };

    $.fn.clearable = function(options) {
        return this.each(function(key, value) {
            var element = $(this);

            if (element.data('clearable')) {
                return element.data('clearable');
            }
            var clearable = new Clearable(this, options);

            element.data('clearable', clearable);

            return clearable;
        });
    };
})(jQuery);