Basic styling select boxes with just a jQuery

Today I worked on project where I needed to do basic custom styling of select box. Oh yea, you know the pain.  I wasn’t able find any simple library, so I have written down my own really basic script.

Find javascript / jQuery script below and working example on codepen.

$(function() {

    var userAgent = window.navigator.userAgent;
    var isSafari = false;
    if (userAgent.match(/iPad/i) || userAgent.match(/iPhone/i)) {
        isSafari = true;
        $('select').addClass('safari');
    }

    if (!isSafari) {

        $('select').each(function() {

            // Wrap selectbox to custom structure and populate current value
            $select = $(this);
            $custom = $('<span class="selectbox"><span class="selectboxvalue"></span></span>');
            $select.after($custom);
            $custom.append($select);
            $custom.find('.selectboxvalue').text($select.find(':selected').text());

            // Define basic styles to behave like select box
            $custom.css({
                position: 'relative',
                display: 'inline-block',
                cursor: 'pointer'
            });

            $select.css({
                display: 'none',
                position: 'absolute',
                top: 0,
                left: 0,
                zIndex: 10,
                minWidth: '100%'
            });

            $select.attr('size', $select.find('option').length);


            // Define controll
            $custom.on('click', function(e) {
                $(this).find('select').show();
            });

            $select.on('click', function(e) {
                var val = $(this).find(':selected').text();
                $(this).prev('.selectboxvalue').text(val);
                $(this).hide();
                return false;
            });

        });

        // Hide select box on click outside
        $(document).click(function(e) {
            console.log(e.target);
            $('.selectbox select').hide();
            if ($(e.target).is('.selectbox')) $(e.target).find('select').show();
            if ($(e.target).is('.selectboxvalue')) $(e.target).next('select').show();
        });

    }
});

Basically, there are two scenarios – styling select box for desktop and styling it for mobile safari. In the first case we wrap select box with custom HTML and hide original select box. In the second case we style select box only using CSS. It’s not all problem solving solution, but handy enough for simple projects. I think the code speaks for itself, so I will leave it with you. Check the codepan example to see it in action.