A Clear Text Input Widget

A simple jQuery UI text input widget that's applied to input elements. It displays a button in the input that clears the text.

HTML

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css">
<input type="text" placeholder="Search"/>

CSS

body {
    font-size: 0.8em;
}

.ui-cleartext {
    padding: 0.2em;
    outline: none;
}

.ui-cleartext-icon {
    cursor: pointer;
}

JavaScript

(function( $ ) {

    // CSS classes applied to the cleartext widget.
    var widgetClasses = [
        "ui-cleartext",
        "ui-widget",
        "ui-widget-content",
        "ui-corner-all"
    ].join( " " ),
    
    // CSS classes applied to the icon span.
    iconClasses = [
        "ui-icon",
        "ui-icon-close",
        "ui-cleartext-icon"
    ].join( " " );
    
    // Define the "cleartext" widget.
    $.widget( "app.cleartext", {
        
        _create: function() {
            
            this._super();
        
            // Apply the widget classes to the input
            // element.
            this.element.addClass( widgetClasses );
            
            // Create and store a reference to the icon
            // span. The span uses icon classes from the theme
            // framework. We're positioning the icon using
            // the position utility.
            this.$icon = $( "<span/>" )
                .addClass( iconClasses )
                .appendTo( "body" )
                .position({
                    at: "right-12",
                    of: this.element
                });
            
            // When the clear icon is clicked.
            this._on( this.$icon, {
                click: "_clear"    
            });
        },
        
        // When the widget is destroyed, remove the
        // icon span, as well as removing the classes
        // from the input element.
        _destroy: function() {
            this.$icon.remove();
            this.element.removeClass( widgetClasses );
        },
        
        // When the clear button is clicked, reset the
        // value, and re-focus the input.
        _clear: function( e ) {
            this.element.val( "" ).focus();
        }
        
    });
    
    $(function( $ ) {
        $( "input" ).cleartext();
    });
    
})( jQuery )