Book Image

Learning jQuery : Better Interaction Design and Web Development with Simple JavaScript Techniques

Book Image

Learning jQuery : Better Interaction Design and Web Development with Simple JavaScript Techniques

Overview of this book

Table of Contents (18 chapters)
Learning jQuery
Credits
About the Authors
About the Reviewers
Preface

The Finished Code


Our completed code for the search field’s presentation and auto-complete behaviors is as follows:

$(document).ready(function() {
  var searchLabel = $('#search label').remove().text();
  $('#search-text').addClass('placeholder').val(searchLabel)
                                                  .focus(function() {
    if (this.value == searchLabel) {
      $(this).removeClass('placeholder').val('');
    };
  }).blur(function() {
    if (this.value == '') {
      $(this).addClass('placeholder').val(searchLabel);
    };
  });
  $('#search').submit(function() {
    if ($('#search-text').val() == searchLabel) {
      $('#search-text').val('');
    }
  });

  var $autocomplete = $('<ul class="autocomplete"></ul>').hide().
insertAfter('#search-text');
  var selectedItem = null;

  var setSelectedItem = function(item) {
    selectedItem = item;
    if (selectedItem === null) {
      $autocomplete.hide();
      return;
    }
    if (selectedItem < 0) {
      selectedItem...