How do I build a gracefully-degrading HTML5 Range?
Asked Answered
N

2

7

I'd like to use the <input type='range' /> from HTML5 for browsers that support it and degrade to a <select /> if not. I'm using Ruby-on-Rails, so failing all else, I could do something like this on the server-side.

I would prefer, though, to have something more inline with the idea of progressive enhancement done via Javascript. Bonus points if it's JQuery.

Nadabas answered 11/2, 2010 at 17:4 Comment(0)
A
5

Check out Modernizr, it will tell you if range is supported. I believe the technique is to create a range input and check it's type — if it is still "range" then it is supported. Otherwise it should report "text" which is the fallback in other browsers.

Aam answered 11/2, 2010 at 22:11 Comment(0)
R
1

First detect if the browser can handle HTML 5 then use something like this:

   $('input').each(function (i, item) {
        if ($(item).attr('min') !== undefined && $(item).attr('max') !== undefined) {
            var select = document.createElement("SELECT");
            $(select).attr('name', $(item).attr('name'));
            $(select).attr('id', $(item).attr('id'));
            $(select).attr('disabled', $(item).attr('disabled'));
            var step = 1;
            if ($(item).attr('step') !== undefined) {
                step = parseFloat($(item).attr('step'));
            }

            var min = parseFloat($(item).attr('min'));
            var max = parseFloat($(item).attr('max'));
            var selectedValue = $(item).attr('value');
            for (var x = min; x <= max; x = x + step) {
                var option = document.createElement("OPTION");
                $(option).text(x).val(x);
                if (x == selectedValue) { $(option).attr('selected', 'selected'); }
                $(select).append(option);
            };
            $(item).after(select);
            $(item).remove();
        }
    });

Since you can't use the input[type=range] selector i had to go with the $(item).attr('min') && $(item).attr('min') approach, this will get a little weird if you have other types of input controls with those two attributes.

Rapp answered 11/2, 2010 at 19:44 Comment(2)
I like it. Perhaps something like jQuery.support.rangeInput = ((jQuery.browser.safari) || (jQuery.browser.opera && jQuery.browser.version >= 2.0)) to check for range input support?Nadabas
I would have preferred progressive enhancement to graceful degradation since it's possible I'd come across a browser that neither supports <input type='range'> nor has Javascript on, so the inputs will never get converted. Still, it at least answers the question.Nadabas

© 2022 - 2024 — McMap. All rights reserved.