Customized search bar in drupal, jQuery vs Preprocess

I wanted a search to bar display ‘Search..’ until clicked in a Drupal site I’m building. jQuery immediately came to mind. As it turns out, jQuery is actually the wrong way to do this under Drupal, but when I first went looking for an answer to this problem I didn’t know that, so I’m going to provide both solutions.

The jQuery solution looks like this entails using the very messy looking jQuery() instead of $() because of drupal:

// check that the document is loaded before initiating changes
jQuery(document).ready(function()
{
  // select the element you want to change,
  // in this case our input with id #edit-search-block-form--2
  jQuery("#edit-search-block-form--2")
    .val("Search...")                                             // change the value to Search...
    .css("color", "#b1b1b1")                                 // and the color of the text to whitish according to the needs of my theme
    .focus(function(){                                          // if in focus, we want to change some properties
        jQuery(this).css("color", "black");               // black so the user doesn't have to squint at the text they're entering
        if (jQuery(this).val() == "Search...") {        // if it's still Search, delete that punk
            jQuery(this).val("");
        }
    })
    .blur(function(){                                            // once back from the anarchy of being in focus
        jQuery(this).css("color", "#b1b1b1");          // set the color back
        if (jQuery(this).val() == "") {                     // and replace our trusty Search...
            jQuery(this).val("Search...");
        }
    });
});

The reason this is wrong is because Drupal is already building this form from scratch with the form api. jQuery is coming in after the fact and wasting our users precious processing power. The correct way to do it is to intercept the form during preprocess, and in my case in my template.php, and attach the javascript functions then.

This entry was posted in Programming and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>