logo

Palette - Make it Colorful🎨

Palette - Visual Page Builder, no design degree required.

Live Demo Download Palette

Scroll

jQuery and Drupal. Lesson 7. Search field on jQuery, events Focus and Blur

16/04/2025, by Ivan

You've probably seen a search field with the word "Search" in it, which disappears when clicked so you can type your query. Below is a jQuery snippet for that functionality:

$('#search-block-form .form-text').val('Search');

$('#search-block-form .form-text').blur(function() {
    if (this.value == '') {
        this.value = 'Search';
    }
});
$('#search-block-form .form-text').focus(function() {
    if (this.value == 'Search') {
        this.value = '';
    }
});

This uses two event handlers: .blur() and .focus().

.blur() handles the event when the input loses focus. If the field is empty, it inserts the word "Search" back into it.

.focus() handles the event when the input gains focus. If the field contains the word "Search", it clears the field.