Off-canvas Menu With JavaScript Example

Off-canvas menu with JavaScript and CSS animated effects. When we will click on the menu toggle button to open the navbar then we will see the navigation bar open as animated.

By using this Off-canvas menu with JavaScript snippet we can show more menu items at the sidebar or header as a menu toggle.

HTML

<div class="offcanvas-menu">
    <!-- Menus Toggle Button -->
    <div class="menu-toggle" onclick="expandmenu()">
        <i class="fas fa-plus" id="menu-toggle"></i>
    </div>

    <!-- Menus list -->
    <div class="menus" id="menus">
        <a href="#">
            <i class="fas fa-home"></i> Home
        </a>
        <a href="#">
            <i class="fas fa-taxi"></i> Services
        </a>
        <a href="#">
            <i class="fas fa-photo-video"></i> Gallery
        </a>
        <a href="#">
            <i class="fas fa-newspaper"></i> News
        </a>
        <a href="#">
            <i class="fas fa-question"></i> Support
        </a>
    </div>
</div>

CSS

.offcanvas-menu {
    display: flex;
    justify-content: center;
    margin: 100px 0px;
}
.menu-toggle {
    border-radius: 20px 0px;
    cursor: pointer;
    background: #03a9f4;
    color: #fff;
    height: 50px;
    width: 50px;
    font-size: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.menu-toggle:hover {
    background-color: #009688;
}
.menus {
    display: flex;
    flex-direction: row;
    transform: scaleX(0);
    transform-origin: left;
    margin-left: 10px;
    transition: 1s;
}
.menus > a {
    text-decoration: none;
    display: flex;
    font-size: 20px;
    color: #474747;
    padding: 0px 10px;
    justify-content: center;
    align-items: center;
    text-transform: none;
    border-right: 1px solid #ddd;
}
.menus > a:hover {
    color: #03a9f4;
}
.menus > a > i {
    margin-right: 10px;
}
.menus > a:last-child {
    border-right: none;
}

JavaScript

var state = false;
function expandmenu() {
    if (state == false) {
        document.getElementById('menus').style.transform = "scaleX(1)";
        document.getElementById('menu-toggle').style.transform = "rotate(45deg)";
        state = true;
    }
    else {
        document.getElementById('menus').style.transform = "scaleX(0)";
        document.getElementById('menu-toggle').style.transform = "rotate(0deg)";
        state = false;
    }
}