How to add a search box to your website's navigation bar

In this tutorial, we will expand upon our previous tutorials on how to build a search engine and navigation bar and learn how to add a search box to the navigation bar. We'll also discuss how to make the search box responsive to differently sized browser windows, to ensure it looks good on all devices.

navbarsearch.png

Moving the search box into the navigation bar

At the end of the tutorial on building a search engine, we added the search box to the middle of the webpage. To move the search box into the navigation bar, cut all the code for the search box (which is contained within the div tags that were assigned the class search-box) and paste it below the links in the navigation bar:

<body>
<div class="navbar">
    <a href="http://treesandtrees.com">Home</a>
    <a href="http://treesandtrees.com/About/">About</a>
    <a href="http://treesandtrees.com/TreeTypes/">Types of Trees</a>
    <div class="search-box">
        <form action="search.php" method="get">
            <input type="text" name="search" maxlength="60" placeholder="Search..." required>
            <button type="submit"><i class="fa fa-search"></i></button>
        </form>
    </div>
</div>

</body>

Complete code

The complete HTML code for the responsive navigation bar with an integrated search box is shown below:

<!DOCTYPE html>
<html lang="en-GB">
<head>
    <title>Home</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="main.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="navexpansion.js"></script>
</head>
<body>
<div class="navbar" id="myTopnav">
    <a href="http://treesandtrees.com">Home</a>
    <a href="http://treesandtrees.com/About/">About</a>
    <a href="http://treesandtrees.com/TreeTypes/">Types of Trees</a>
    <div class="search-box" id="search-responsive">
        <form action="search.php" method="get">
            <input type="text" name="search" maxlength="60" placeholder="Search..." required>
            <button type="submit"><i class="fa fa-search"></i></button>
        </form>
    </div>
    <a href="javascript:void(0);" class="icon" onclick="expansion();search_expand()">
        <i class="fa fa-bars"></i>
    </a>
</div>
</body>
</html>

The complete navbar.js JavaScript file:

function expansion() {
    var x = document.getElementById("myTopnav");
    if (x.className === "navbar") {
        x.className += " expanded";
    } else {
        x.className = "navbar";
    }
}
	
function search_expand() {
    var x = document.getElementById("search-responsive");
    if (x.className === "search-box") {
        x.className += " expanded";
    } else {
        x.className = "search-box";
    }
}

<<< Previous

Next >>>