2016-10-06

Website owners very often decide on using Google's Custom Search Engine (GCSE) for searching through their content instead of using built-in and/or custom search functionality. The reason is simple - it's much less work, and most often it does the trick. If you don't need advanced filters or custom search parameters then GSCE is for you.

In this quick tip, I will show you how to manually render the search form (without using a special GCSE tag) and a results box which allows for more control and a cleaner way to style the search input field.

The Problem

Usually adding GCSE to your site is as simple as copy pasting a script and a custom HTML tag into your site. In the place where you put the special GCSE tag, an input search field will render. Typing and starting a search from this field will do a Google search based on previously configured parameters (e.g. search sitepoint.com only).

One question that often comes up is "How do I change the placeholder of the GCSE input field?". Unfortunately very often the suggested answer is wrong as it uses an unreliable setTimeout method in order to wait for the Ajax call from the GCSE to complete (making sure the input is already attached to the DOM) and then changes attributes via JavaScript.

We are also going to query the element and change the attributes with JS, but instead of doing a blind setTimeout() we will use the callback provided by the GCSE which will guarantee that the input has already loaded.

Creating a GCSE Account

The search engine is configured completely online. The first step is to go to the GCSE site and click add. Follow the wizard by filling in the domain on which you want to search (usually your site URL). You can ignore any advanced settings for now.

When you click done, you are presented with three options:

Get Code, which will guide you through what and where you have to copy in order for the search to show on your site

Public URL will show you a working preview of the search that you set up

Control Panel for customising the search

Go to Control Panel, click Search Engine ID and make a note of this value for later.

HTML Setup

In order to try this out, we will create a basic index.html containing the HTML needed and an app.js file containing the functions needed to render and customise the search.

Go ahead and create a basic HTML file with this inside:

We added two <div>'s with special classes in order to be recognized as the elements where the search form and results should be rendered.

Continue reading %Quick Tip: How to Style Google Custom Search Manually%

Show more