jQuery: creare un plugin per personalizzare le select box

Con jQuery possiamo creare un plugin per le select box personalizzate.

Dobbiamo nascondere in modo accessibile la select box ed inserire prima di tale elemento un menu di navigazione personalizzato.


(function( $ ) {
    $.fn.myCustomSelect = function( options ) {
        options = $.extend({
            wrapperClass: "custom-select",
            toggleClass: "custom-select-toggle",
            toggleText: "Choose an option",
            linkClass: "custom-select-link",
            onSelect: function() {}
        }, options);

        var hideAccessible = function( element ) {
            var css = {
                position: "absolute",
                top: "-99999em",
                width: "0px",
                height: "0px",
                overflow: "hidden"
            };
            element.css( css );
        };

        var createCustomSelect = function( element ) {
            var html = '<nav class="' + options.wrapperClass + '" aria-hidden="true">';
            html += '<a href="#" class="' + options.toggleClass + '">' + options.toggleText + '</a>';
            html += '<ul style="display: none;">';
            
            element.find( "option" ).each(function() {
                html += '<li><a href="#" class="' + options.linkClass + '" data-value="' + $( this ).val() + '">' + $( this ).text() + '</a></li>';
            });
            html += '</ul>';
            html += '</nav>';

            element.before( html );
        };

        var handleEvents = function( element ) {
            $( document ).on( "click", "." + options.toggleClass, function( e ) {
                e.preventDefault();
                if( $( this ).next().is( ":hidden" ) ) {
                    $( this ).next().fadeIn();
                } else {
                    $( this ).next().fadeOut();
                }
            });
            $( document ).on( "click", "." + options.linkClass, function( e ) {
                e.preventDefault();
                var value = $( this ).data( "value" );
                element.val( value );
                options.onSelect( value, element );
            });
        };

        return this.each(function() {
            var $element = $( this );
            handleEvents( $element );
            hideAccessible( $element );
            createCustomSelect( $element );
        });
    };
})( jQuery );

Esempio d'uso:


$( function() {
    $( "#country" ).myCustomSelect({
        onSelect: function( value, select ) {
            console.log( value );
        }
    });
});