How to Create Horizontal Scrolling Menu using jQuery and PHP

Last modified on July 24th, 2019 by Vincy.

Menu is an integral component of a website. It is the gateway for users to explore the pages. Primary menu is part of the header and one of the most prominent item that gets the user attention first.

We need to to get it right. When there are huge number of categories and so pages, then it is difficult to craft the menu so that the users can easily navigate them.

Horizontal scrolling menu is a solution for the scenario of long list of items in a single menu bar.

Numerous amount of third party plugins or libraries are available in the market for implementing scrolling menu feature for your application.

Nothing beats our custom code. In this article, we are going to see how a simple horizontal scrolling menu can be built easily with an example. 

Horizontal Scrolling Channel Menu

View Demo

The menu interface is made as scrollable by the use of CSS and jQuery animation. The scrolling property is added to the menu container via CSS and the horizontal scroll position is managed by jQuery script to create an animation effect. Previously, we have created horizontal menu with expand collapse effect using jQuery.

What is inside?

  1. Uses of horizontal scrolling menu
  2. Available plugins and libraries to enable horizontal scrolling
  3. Advantages of using custom code to implement horizontal scrolling
  4. About this menu example
  5. Code implementation to show menu with horizontal scrolling
  6. HTML code to display menu
  7. jQuery script to handle horizontal scrolling
  8. Fetch menu items from the database using PHP MySQL
  9. File Structure
  10. Database script
  11. Horizontal scrolling menu output

Uses of horizontal scrolling menu

As we already seen in the introductory part, the horizontal scrolling menu will be a perfect solution for some specific use cases. Some of those cases are listed below.

  • It will be suitable for creating a responsive menu for making the menu interface fluid about web or mobile browser view ports.
  • Horizontal scrolling menu is a best method of showing a long list of menu items in a single without scrollbar.
  • It prevents the menu item list from wrapping to the next line which will be good while considering about vertical spacing and aesthetics.
  • When there is a long list of categories in a shopping cart software, horizontal scrolling menu will be handy.

Available plugins and libraries to enable horizontal scrolling

There are huge variety of jQuery JavaScript Bootstrap plugins for creating scrolling menu div or list items. Some of those plugins gives controls to choose the scrolling axis and direction.

Smooth Div ScrolljQuery Horizontal Scrollbars are some of the example plugins provides horizontal scrolling feature. By integrating any one of such plugin we can map/initialize our menu HTML element object to apply horizontal scrolling property on our menu bar.

Advantages of using custom code to implement horizontal scrolling

Though the external plugins give modern, amazing and interactive scrolling menu, they will be heavy and let us depend on its updates. 

  • Own customization will always simplifies the code and minimize the number of files files.
  • Compared to the dedicated third-part plugins, the custom code flow will be easy to understand.
  • Sometimes, the horizontal scrolling menu plugins CSS or JS may override the existing application scripts and collapse the layout or behavior or both. It will be greatly avoided by using own code. 
  • The menus are aligned in center with use of css text-align. The previous navigation are floated at left side and also next navigation are floated at the right corner using the css float property.
  • The both navigation are placed inside in the separate div part to avoid disturbing behind the menus.

Because of these flexible aspects, I always prefer to use custom code as much as possible instead of depending any third party libraries.

About this menu example

In this example, I didn’t use any heavy third party libraries except the renowned unbeatable jQuery.  The scrolling menu items are dynamic from the database. I used PHP, MySQL to show dynamic menu items from the database.

This is a basic and simple example code of creating dynamic scrolling menu. It will be easy to understand the code used in this example. The jQuery methods are used for handling horizontal scrolling and animation. 

In the menu bar HTML a previous next navigation controls are added to scroll menu horizontally. On the click event of these controls, the jQuery animate() method is called to move the menu items back and forth.

Code implementation to show menu with horizontal scrolling

The horizontal scrolling menu code contains the following UI elements.

  1. The left right navigation controls
  2. Scrollable menu bar

The two navigation controls are rendered on top of the scrollable menu bar layer. They are positioned absolutely to the right and left side of the menu bar. In a previous article, we have seen code for displaying sliding menu by managing the CSS position dynamically.

Initially, a limited number of menu items will be displayed in the menu bar based on the screen width. The right navigation control is used to scroll the menu menu bar horizontally and to see more menu items on the right.

HTML code to display the scrolling menu

In this section, let us see the HTML code used to display the menu interface to the user. In this HTML, it contains left right navigation elements and a list of dynamic menu items.

The left right svg arrow images are used here as the navigation controls. And the array of menu items retrieved from the database are iterated to display horizontally.

The navigation elements id is used as a reference to handle the menu scroll towards left or right accordingly.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1"></head>
    <body>
        <link href="./style.css" rel="stylesheet" type="text/css">   
        <nav id="menu-container" class="arrow">
    <div id="btn-nav-previous" style="fill: #FFF">
        <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"
            viewBox="0 0 24 24">
                <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z" />
                <path d="M0 0h24v24H0z" fill="none" /></svg>
    </div>
    <div id="btn-nav-next">
        <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"
            viewBox="0 0 24 24">
                <path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z" />
                <path d="M0 0h24v24H0z" fill="none" /></svg>
    </div>
    <div class="menu-inner-box">
        <div class="menu">
                        <?php foreach($result as $res){ ?>
                        <a class="menu-item" href="#"><?php echo $res['menu']; ?></a>
                        <?php  } ?>
                    </div>
    </div>
</nav>
    </body>
</html>

This example is created responsive menu by using the CSS media queries shown below.

body {
    font-family: arial;
    max-width: 996px;
    margin: 70px auto;
}
nav#menu-container {
    background:#586e75;
    position:relative;
    width:100%;
    height: 56px;
}
#btn-nav-previous {
    text-align: center;
    color: white;
    cursor: pointer;
    font-size: 24px;
    position: absolute;
    left: 0px;
    padding: 9px 12px;
    background: #8f9a9d;
    fill:#FFF;
}
#btn-nav-next {
    text-align: center;
    color: white;
    cursor: pointer;
    font-size: 24px;
    position: absolute;
    right: 0px;
    padding: 9px 12px;
    background: #8f9a9d;
    fill:#FFF;
}
.menu-inner-box
{ 
    width: 100%;
    white-space: nowrap;
    margin: 0 auto;
    overflow: hidden;
    padding: 0px 54px;
    box-sizing: border-box;
}
.menu
{  
    padding:0;
    margin: 0;
    list-style-type: none;
    display:block;
    text-align: center;
}
.menu-item
{
    height:100%;
    padding: 0px 25px;
    color:#fff;
    display:inline;
    margin:0 auto;
    line-height:57px;
    text-decoration:none;
    text-align:center;
    white-space:no-wrap;
}
.menu-item:hover {
    text-decoration:underline;
}

@media only screen and (max-width: 480px) {
  #btn-nav-previous {
    display:none;
  }
  #btn-nav-next {
    display:none;
  }
    .menu-inner-box
    { 
        width:100%;
        overflow-x:auto;
    }
}

jQuery script to handle horizontal scrolling

The following jQuery script shows the simplicity of this example. Also it tells the way the horizontal scrolling animation is implemented with a few lines of code.

In jQuery the animate() is one of the frequently used functions to perform animation with the set of CSS properties. For this horizontal scrolling menu, this method is called with the scrollLeft CSS property.

Based on the navigation control clicked by the user, the scrollLeft of the menu element will be increased or decreased accordingly. It will be shown to the user as an animation effect.

We can also specify duration on which speed the animation to be taken place.

>script src="./jquery-3.2.1.min.js"<>/script<
>script<
    $('#btn-nav-previous').click(function(){
        $(".menu-inner-box").animate({scrollLeft: "-=100px"});
    });
    
    $('#btn-nav-next').click(function(){
        $(".menu-inner-box").animate({scrollLeft: "+=100px"});
    });
>/script<

Fetch menu items from the database using PHP MySQL

This is very common practice when we want to display dynamic data from the database to the UI.

This PHP code snippet will be added to the code before menu HTML.

The DBController.php is for creating database connection object and execute queries to retrieve menu data. So it is included before creating the SELECT query for retrieving menu result.

The method runQuery will return the array of menu items and it is stored in aPHP variable. This menu variable will be later iterated in a PHP loop to display the horizontal scrolling menu items.

<?php
require_once 'DBController.php';
$db_handle = new DBController();

$query = "SELECT * FROM tbl_menu";
$result = $db_handle->runQuery($query);
?>

DBController.php

<?php
class DBController
{

    private $host = "localhost";

    private $user = "root";

    private $password = "";

    private $database = "phpsamples";

    private $conn;

    function __construct()
    {
        $this->conn = $this->connectDB();
    }

    function connectDB()
    {
        $conn = mysqli_connect($this->host, $this->user, $this->password, $this->database);
        return $conn;
    }

    function runQuery($query)
    {
        $result = mysqli_query($this->conn, $query);
        while ($row = mysqli_fetch_assoc($result)) {
            $resultset[] = $row;
        }
        if (! empty($resultset))
            return $resultset;
    }
}
?>

File Structure

This example includes the following files for implementing the horizontal scrolling menu. The index.php is the landing page which contains the menu HTML.

The data for the scrolling menu is fetched from the database using the DBController.php class files. 

Horizontal Scrolling Menu File Structure

Database script

The below SQL script shows the create statement and the data for the menu database table. This script is included in the downloadable source code with menu.sql file.

Import this table into your development environment using PHPMyAdmin or any other client.

For setting up this example in your PHP environment this database is required to be imported before running this example.

--
-- Table structure for table `tbl_menu`
--

CREATE TABLE `tbl_menu` (
  `id` int(11) NOT NULL,
  `menu` varchar(30) CHARACTER SET latin1 COLLATE latin1_bin NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_menu`
--

INSERT INTO `tbl_menu` (`id`, `menu`) VALUES
(1, 'Home'),
(2, 'Browse'),
(3, 'My Account'),
(4, 'Search'),
(5, 'Settings'),
(6, 'Contact Us'),
(7, 'Products'),
(8, 'Tutorials'),
(9, 'Blog'),
(10, 'Question and Answer'),
(11, 'Feedback'),
(12, 'Services'),
(13, 'Our Clients'),
(14, 'Porfolio'),
(15, 'Tour'),
(16, 'History'),
(17, 'Logout');

--
-- Indexes for table `tbl_menu`
--
ALTER TABLE `tbl_menu`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_menu`
--
ALTER TABLE `tbl_menu`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18;
COMMIT;

Horizontal scrolling menu output

The screenshot shows the horizontal scrolling menu. The menu database contains more than ten menu entries. But in the screenshot we could see some of them on initial page load.

The rest of the items could be seen by scrolling the menu by using the right navigation button. The left right navigation buttons on both side of the menu bar will be used to scroll the menu back and forth.

How to Create Horizontal Scrolling Menu using jQuery and PHP

Conclusion

Creating a horizontal scrolling menu for your application is a simple job as it requires only few tools and experience on UI with basic knowledge on HTML, CSS and jQuery. Hope this tutorial will give you the confidence to attempt creating this by your own.

All the menu items used in this example has pointed as # for their href attribute. We can enhance the menu behavior by highlighting the currently clicked menu item.

As discussed already, there are components providing this scrolling feature for the UI elements. All about your call to make decision between site heaviness and aesthetics. If your site is already loaded with Bootstrap, jQuery UI like libraries, then it would be good choice of integrating Bootstrap based scrolling menu component you found online.

This scrolling menu code supports infinite list of menu items. You can create new menu entries in the database and test this feature after setting this up in your development environment.

View Demo Download

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this Article