The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time. -- Tom Cargill

How to Integrate a Google Custom Search Popup In a Bootstrap Navbar

Downloads

  • Bootstrap_CSE_Complete.zip (1.7KB) - This download contains a single HTML file which represents the complete and final result of working through this tutorial.

Intro

It was a bigger task than I expected, integrating Google Custom Search for websites with the Bootstrap 3 navbar.

While many forums and websites discussed parts of the solution, none captured everything that was needed to make this work.

This article is intended to be a comprehensive reference from start to finish suitable for even a Bootstrap noob like myself.

Bootstrap is a Nice Framework

Bootstrap is obviously a powerful framework. If all it did was standardize a list of common CSS class names, that would be enough to make it useful.

But throw in the support for responsive design and some of the javascript goodies (without the need to touch javascript code) and it's a superstar.

There's a reason adoption of the framework has nearly doubled over the past year and can now be found on 10% of the top 10,000 websites on the web.

Motivation

After seeing a nice modal search dialog on another website I decided to see if I could implement something similar using the Bootstrap nav bar and Google's free Custom Search Engine.

In this tutorial I will work with pure HTML and CSS to keep it simple. I'm sure you can take it from here if needed.

Step #1 - The HTML Shell

First you need to create the basic HTML page and include Bootstrap along with a couple of shims recommended by the Bootstrap website.

Bootstrap consists of one CSS file and one javascript file. You'll need to include both on the page.

<!-- http://www.CambiaResearch.com  -->
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
        <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body>

    <div id="mainBodyContent" class="container-fluid">

        <!-- Your content will go here. -->

    </div>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

</body>
</html>

As you can see we've included version 3.3.5 of Bootstrap from a CDN. The CSS link is in the head and we put the Bootstrap javascript include at the bottom of the page along with jQuery which is required.

Version 3.3.5 of Bootstrap requires jQuery 1.9.1 or higher.

Step #2 - Navbar shell

Next, let's insert a basic Bootstrap navbar. We'll do this with the nav element and apply the various Bootstrap classes that tell Bootstrap to apply its navbar styling.

Insert the following code where it says "Your content will go here."

<nav class="navbar navbar-fixed-top navbar-default">
   <div class="container-fluid">
       <div class="navbar-header">
           <!-- Your navbar header related stuff will go here. -->
       </div>
       <div>
           <!-- Your menu items will go here. -->
       </div>
   </div>
</nav>

I have chosen to apply the navbar-fixed-top class to my navbar so it will lock itself to the top of the browser viewport even when I scroll down the page.

Within the nav element we have a single div which will contain all of our navbar content.

Inside that we have two more divs, a header div and one which will contain all of our menu items.

Here is what our navbar looks like so far. It's just a line of gray about 50 pixels high.

Let's start adding stuff.

Step #3 - Add Site Name

We start by adding our site brand. This is a special entity to Bootstrap and by default is positioned on the left side of the navbar.

We'll just add our site name with a little styling for a nice effect.

Add the following code where it says "Your navbar header related stuff will go here."

<a class="navbar-brand" style="font-weight: bold;" href="http://www.cambiaresearch.com">
   <span style="color: #00667F;">Cambia</span><span style="color: #A2CD3A;">Research</span>
</a>

It's just a link with some colored text and the navbar-brand class applied.

This is what our navbar looks like now.

Step #4 - Add Some Menu Items

Now, where it says "Your menu items will go here," copy the following code.

We're adding three menu items: Projects, Articles and About. This are just a list of links where the special Bootstrap classes nav and navbar-nav are applied to the list.

<ul class="nav navbar-nav">
   <li><a href="http://www.cambiaresearch.com/projects">Projects</a></li>
   <li><a href="http://www.cambiaresearch.com/articles">Articles</a></li>
   <li><a href="http://www.cambiaresearch.com/articles/66/about-cambia-research">About</a></li>
</ul>

We now have some menu items...check it out!

If you shrink the width of your browser now, you'll see that the menu converts from horizontal to vertical in a responsive way that is better for smaller devices. This is out-of-the-box behavior.

Step #5 - Add a Login Button on the Right Side

Let's get a little fancier now and add a basic Login button which will sit on the right side of the navbar.

We'll also include the log-in glyph icon to make things a little more visually friendly.

Add the following ul list element beneath the one you just added. We'll now have two lists within the menu item div. The first list will align left and this list will align right. Bootstrap provides the navbar-right class to make this happen.

<ul class="nav navbar-nav navbar-right">
   <li>
       <a href="http://www.cambiaresearch.com/login">
           <span class="glyphicon glyphicon-log-in"></span> Login
       </a>
   </li>
</ul>

Now we have a nice Login button on the right of our navbar.

Alright, things are shaping up. Let's move on now to our search functionality.

Step #6 - Add a Search Button

We have several things to do for our search functionality, but we'll start by adding a search button.

To do this, we'll just insert a fourth list item into our first list.

When you're done, your list HTML should look like the following. Note that all we've done is add the fourth item. You are replacing the existing list with the following code. (Or I suppose you could just copy and paste the fourth item. Decisions, decisions.)

There is no value for the href yet because... well, because we don't know what to point to yet.

In theory, you could point to a Google hosted search page for your site, but we're going to do something a little more interactive.

<ul class="nav navbar-nav">
   <li><a href="http://www.cambiaresearch.com/projects">Projects</a></li>
   <li><a href="http://www.cambiaresearch.com/articles">Articles</a></li>
   <li><a href="http://www.cambiaresearch.com/articles/66/about-cambia-research">About</a></li>
   <li>
       <a href="">
           <span id="searchGlyph" class="glyphicon glyphicon-search"></span>
       </a>
   </li>
</ul>

Here's the updated navbar.

Do you see the magnifying glass icon? Good.

Step #7 - Collapse the Menu on Small Screens

I won't bother to explain too much here, but in the interest of completeness let's configure Bootstrap to collapse our menu to a nice little menu icon for smaller screens. I love this feature.

In the div with class="navbar-header" add the following HTML. I inserted it above the link with class="navbar-brand".

This button will serve as our menu icon on smaller screens.

<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
  <span class="icon-bar"></span>
  <span class="icon-bar"></span>
  <span class="icon-bar"></span>
</button>

You can see that the button contains an attribute data-target="#myNavbar".

This selector needs to point to our main navbar div that contains all of our menu items.
Therefore, we need to add ID="myNavbar" to that div. Plus, we need a couple of additional Bootstrap classes to support the collapsed menu, collapse and navbar-collapse.

You'll need to add the class and id attributes to the div in the following code sample. The list (ul) is only shown for context.

<div class="collapse navbar-collapse" id="myNavbar">
  <ul class="nav navbar-nav">
      <li><a href="http://www.cambiaresearch.com/projects">Projects</a></li>
       ...
</div>

Now when the screen width is small, our menu automatically converts from showing all of the menu items to only showing the simple menu icon.

Hmmm...

Now the search icon looks funny there all by itself. In this mode, it really needs some text to balance off against the Login menu item.

Let's add a text label for the search icon that will only display when the menu is collapsed.

We can do this by adding a span and some Bootstrap classes that will hide the text for all browser widths except the smallest, which is when the collapsed menu gets displayed.

Bootstrap supports a set of four classes named "hidden-*" where the * is xs, sm, md or lg for extra-small, small, medium and large. We'll apply all but the smallest to only allow the text to display when the browser width is extra-small.

Update the hyperlink for your search icon as follows:

<a href="">
  <span id="searchGlyph" class="glyphicon glyphicon-search"></span> <span class="hidden-sm hidden-md hidden-lg">Search</span>
</a>

Notice that all we did was add the span that contains the text "Search".

Now we get a menu that looks like this:

Step #8 - Modal Dialog Shell

I've decided I would like a modal dialog to display when the user clicks the search icon.

We can use Bootstrap's built in support for modal dialogs, so we'll need to create the basic HTML that will be used for the modal dialog.

Insert the following HTML content beneath the nav element in your page.

<!-- Search Modal -->
<div id="modalSearch" class="modal fade" role="dialog">
   <div class="modal-dialog">

       <!-- Modal content-->
       <div class="modal-content">
           <div class="modal-header">
               <button type="button" class="close" data-dismiss="modal">&times;</button>
               <h4 class="modal-title">Search Cambia Research</h4>
           </div>
           <div class="modal-body">
               <!-- Add the modal body here -->
           </div>
           <div class="modal-footer">
               <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
           </div>
       </div>

   </div>
</div>

Since this is not a tutorial on the Bootstrap modal dialog, I won't go into too much detail here.

Just observe that there are several Bootstrap classes applied to the div including modal, fade, modal-content, modal-header, modal-body, modal-footer.

For a nice look and feel, I've decided to include a header and footer.

I've also included some content in those header and footer divs including a title, close icon and close button.

The appearance of our page does not change with this addition. That's because the Bootstrap classes hide the modal div until it is activated.

Step #9 - Make the Search Button Open the Modal Dialog

At this point, we're ready to wire up our search button.

Find the hyperlink representing your search icon in the list and replace it with the following code.

<a href="#modalSearch" data-toggle="modal" data-target="#modalSearch">
  <span id="searchGlyph" class="glyphicon glyphicon-search"></span> <span class="hidden-sm hidden-md hidden-lg">Search</span>
</a>

The new additions are the attributes on the hyperlink element <a>.

First, you can see that our href attribute now contains a CSS-style selector (#modalSearch) which points to the element with the ID="modalSearch". That's the modal HTML you just added.

You'll also notice the data-toggle and data-target attributes. data-toggle just indicates that this should be a modal dialog.

The value for data-target is the same as for the href. And yes, it basically tells Bootstrap the same thing, which modal content to activate. This is redundant. I believe part of the reason is that the href was not supported in previous versions of Bootstrap. I tested both by removing each and found that the mouse cursor wasn't correct in one case. Having both works well, so I'd recommend this for now.

Great! Now we have a functioning modal popup dialog when we click the search button.

This is what it looks like.

Step #10 - Add Google Custom Search Code to Modal Dialog

At this point you'll need a google account. Login at http://www.google.com/cse and create a new website search.

In the Look & Feel section choose the Full width option and get the code.

Insert that code where it says: "Add the modal body here."

When you're done the modal-body div should be similar to the following. Its entire content is the script you get from Google.

<div class="modal-body">
   <!-- Replace the following with your own search script from https://www.google.com/cse. -->
   <script>
       (function ()
       {
           var cx = '008246143810435871214:nr0bhziz1xo';
           var gcse = document.createElement('script');
           gcse.type = 'text/javascript';
           gcse.async = true;
           gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
               '//cse.google.com/cse.js?cx=' + cx;
           var s = document.getElementsByTagName('script')[0];
           s.parentNode.insertBefore(gcse, s);
       })();
   </script>
   <gcse:search></gcse:search>
</div>

Now try your modal again. This time you get something resembling a search box in your modal dialog.

However, there is one problem.

If you look closer at the above screen capture you'll see that the Google search button doesn't render properly. The browser is Internet Explorer, but it's a problem in Chrome as well and, I assume, others.

This problem is caused by a conflict between Google CSS and Bootstrap CSS.

The easiest way to fix the problem is to add some custom CSS that will override existing styles and allow the search box and button to render correctly.

Insert the following style block in the modal-body div below the Google code you just added.

This CSS was tricky to get right. There are several websites where users have attempted to provide solutions, but all fell short in some capacity. This CSS fixes all the issues for me in IE and Chrome. There's probably even a better way, but this will do for now.

<!-- These styles fix CSE and Bootstrap 3 conflict -->
<style type="text/css">
    .reset-box-sizing, .reset-box-sizing *, .reset-box-sizing *:before, .reset-box-sizing *:after,  .gsc-inline-block
    {
        -webkit-box-sizing: content-box;
        -moz-box-sizing: content-box;
        box-sizing: content-box;
    }
    input.gsc-input, .gsc-input-box, .gsc-input-box-hover, .gsc-input-box-focus, .gsc-search-button
    {
        box-sizing: content-box;
        line-height: normal;
    }
</style>

All better.

Step #11 - Take It For a Test Drive

Finally, let's take it for a test drive.

Click the search icon and type a search term in the box.

View the lovely results.

When a user clicks on a search result they are whisked directly to the chosen page in a new browser tab.

Bonus #1 - Modal Width Tweaks (Optional)

If the standard modal dialog is too narrow, you can update the width by adding your own styles for .modal .modal-dialog as follows.

This change works nicely at all screen widths.

<style>
  .modal .modal-dialog
  {
      width: 90%;
      margin-left: auto;
      margin-right: auto;
  }
</style>

If you don't like the modal dialog stretching to the full browser width on large screens, you might want to set a fixed width on large screens and allow the dialog to narrow for smaller screens.

Suppose we want the width to be 800px if a screen can support it, but narrow to 95% of the screen width on smaller screens. Try the following.

This CSS is also nicely responsive as the screen width narrows.

<style>
  .modal .modal-dialog
  {
      width: 800px;
      max-width: 95%;
      margin-left: auto;
      margin-right: auto;
  }
</style>

View the result below. The dialog width is 800px on a wide screen, but no wider. And 95% of the full width on smaller screens.

Bonus #2 - That Pesky Search Button Outline (Optional)

Click the search button to open the modal dialog window. Now click the close button to close. Have a look at the magnifying glass icon. There's a border around it.

I don't know about you, but I find that pretty annoying. This border is even more prominent in the Chrome browser.

Add the following CSS to remove it.

<!-- Prevents outline of search button when modal is closed -->
<style>
   .modal-open .modal, a:focus
   {
       outline: none !important;
   }
</style>

Conclusion

For me, this popup search solution is a very user friendly approach to site search which avoids extra page loads so that the user can discover what they want quicker.

However, you can see that this tutorial was a bit of a trek. While it was way easier than coding the javascript and CSS myself, there were still several gotchas that were not adequately addressed by any web search I did looking for the answers.

Hopefully, this will make the whole process easier for you.

And if you'd rather just look at code, be sure to download the completed sample project near the top of this article.

If you have any thoughts or additions, please share in the comments below.

 

Version: 6.0.20200920.1535