Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html5 input type number: detect whether spinbox or not (and no other features)

In Webkit browsers, an input[type=number] has a spinbox control:

spinbox control in webkit browsers

However, Safari does not follow some other input[type=number] rules, like enforcing that only numeric characters are entered. Hence, Modernizr detects that Safari does not support input[type=number].

I have very particular needs for number-input width, and when there's a spinbox I make the width 2.7em and without it (like in Firefox), the width need only be 1.7em. So Chrome and Firefox both look fine. But Safari puts in a spinbox but doesn't follow any other rules, so it gets the 1.7em width and looks like this:

number input in Safari

I only care if there's a spinbox control. I don't care about any of the other input[type=number] rules that Safari is flouting. Safari is playing by the only rule I care about. How do I detect that?

like image 272
chadoh Avatar asked Mar 19 '11 16:03

chadoh


1 Answers

I suggest hiding the spinbox when Modernizr doesn't detect support for number inputs:

JS:

if (!Modernizr.inputtypes.number) {
    $('body').addClass('no-number-input');
}

CSS:

.no-number-input input::-webkit-outer-spin-button,
.no-number-input input::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0; 
}

If you really want to detect whether the spinbox is visible you can do something like:

window.getComputedStyle(input, '-webkit-inner-spin-button').getPropertyValue('-webkit-appearance') != 'none'

where input is a "raw" element, although this may not be very reliable, e.g. in Safari for Windows.

like image 173
Jeffery To Avatar answered Nov 17 '22 05:11

Jeffery To