Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Dive Into HTML5 [1] demonstrates how one can detect placeholder support; the obvious use case is to use the focus and blur events to mimic the functionality if native support isn't present.

Here's some example code, using Ojay [2].

    /**
     * Places the label for a text field within that field, for a simpler
     * and more intuitive interface to e.g. search forms.
     */
    var labelInField = function(field) {
        var input = Ojay(field), label = Ojay.Forms.getLabel(field).hide();
        if (!label.node || !input.node) return;
    
        var labelText = label.node.innerHTML.stripTags(),
            inputType = input.node.type || 'text';
    
        // Don't bother setting up the event handlers if the browser can detect
        // the HTML5 placeholder text.
        if ('placeholder' in document.createElement('input') && input.node.placeholder.length > 1) return;
    
        var focus = function() {
            input.removeClass('empty');
            if (input.node.value == labelText) input.node.value = '';
        };
    
        var blur = function() {
            if (input.node.value && input.node.value != labelText) return;
            input.addClass('empty');
            if (inputType == 'text') input.node.value = labelText;
        };
    
        blur();
    
        input.on('focus', focus);
        input.on('blur', blur);
    };
[1] http://diveintohtml5.org/forms.html#placeholder

[2] http://ojay.othermedia.org/



Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: