Placeholder for the searchbox()

About the template and stylesheet - and changing the menu
Post Reply
cmb
Posts: 14225
Joined: Tue Jun 21, 2011 11:04 am
Location: Bingen, RLP, DE
Contact:

Placeholder for the searchbox()

Post by cmb » Sat Aug 18, 2012 6:13 pm

Hello Community,

HTML5 introduced the placeholder attribute for inputs. This can be used to give a hint, what to enter to the input field. It is well suited for the search input, particularly if the search button should be omitted or is a graphic. Unfortunately the placeholder attribute isn't implemented on IE<=9. But one can accomplish the same effect with some JS. So I've played a bit around, and found a solution that will work on browsers which implement the placeholder attribute, and offers a JS based fallback for others.

If you want to try it, add the following function to cmsimple/userfuncs.php (create the file, if it doesn't exists and put <?php at the top):

Code: Select all

function searchbox_with_placeholder($text) {
    global $sn, $tx;
    return '<form action="' . $sn . '" method="GET">' . "\n"
        . '<div id="searchbox">' . "\n"
        . '<script type="text/javascript">function supports_input_placeholder() {
  var i = document.createElement(\'input\');
  return \'placeholder\' in i;
}</script>'
. tag('input type="text" class="text" name="search"
    size="14" placeholder="'. $text .'"
    onfocus="if(!supports_input_placeholder())if (this.value==this.placeholder){this.value=\'\';
            this.style.color=\'#000\'}"
    onblur="if(!supports_input_placeholder())if (this.value.length == 0){this.value=this.placeholder;
           this.style.color=\'#888\'}"
')
. '<script type="text/javascript">
if (!supports_input_placeholder()) {
    var cb = function() {
        var i = document.getElementsByName("search")[0];
        if (i.value.length == 0) {
            i.value=i.placeholder;
            i.style.color=\'#888\'
        }
        i.blur();
    }
    if (window.addEventListener) {
        window.addEventListener("load", cb, false)
    } else {
        window.attachEvent("onload", cb)
    }
}
</script>'
        . tag('input type="hidden" name="function" value="search"') . "\n" . ' '
        . tag('input type="submit" class="submit" value="' . $tx['search']['button'] . '"') . "\n"
        . '</div>' . "\n" . '</form>' . "\n";
} 
Replace the call to searchbox() in the template with searchbox_with_placeholder('search for...').

Christoph

PS: To validate this requires the HTML5 doctype.
Christoph M. Becker – Plugins for CMSimple_XH

Post Reply