Is it possible to activate a lottie hamburger/menu animation by clicking on a .nav-link?

PROBLEM SOLVED, CHECK OUT MY SOLUTION BELOW

Hello there! I've got my navigation working smoothly with one little exception - the lottie animation doesn't revert back to its original frame when the links are clicked.

I've been struggling with finding a solution for this issue for quite some time now. Can anyone offer assistance?

For reference, here is my navigation toggler button using Bootstrap:

<button
        class="navbar-toggler"
        type="button"
        data-bs-toggle="collapse"
        data-bs-target="#lowetoggle"
        aria-controls="lowetoggle"
        aria-expanded="false"
        aria-label="Toggle navigation"
      >
      <div class="lowe-menu" style="width: 50px;"></div>
      </button>
<lottie-player id="toggleLottie" src="assets/menu.json" style="width:50px;">"></lottie-player>
</button>

Below, you'll find the JavaScript code I'm using:

let iconMenu = document.querySelector('.lowe-menu');

let animationMenu = bodymovin.loadAnimation({
        container: iconMenu,
        renderer: 'svg',
        loop: false,
        autoplay: false,
        path: "/assets/menu.json"
});

var directionMenu = 1;
  iconMenu.addEventListener('click', (e) => {
  animationMenu.setDirection(directionMenu);
  animationMenu.play();
  directionMenu = -directionMenu;
});

var navLinks = document.querySelectorAll('.nav-link')
var menuToggle = document.getElementById('lowetoggle')
var bsCollapse = new bootstrap.Collapse(menuToggle, {toggle:false})

navLinks.forEach((l) => {
    l.addEventListener('click', () => { bsCollapse.toggle() })
});

Answer №1

Creating a Bootstrap 5 Lottie Hamburger Menu

I discovered the solution to this issue on my own. If you are using Lottie for your hamburger menu in Bootstrap and have anchor links set up to scroll to different sections, this code snippet will allow the hamburger menu to close when clicking on a .nav-link element.

This information may prove helpful as I couldn't find any other resources online that offered a similar snippet! Perhaps I didn't search far enough!

let iconMenu = document.querySelector('.lowe-menu');
    
    /* Bodymovin animationMenu setup */
    
    var directionMenu = 1;
      iconMenu.addEventListener('click', (e) => {
      // Animation toggle logic
		animationMenu.setDirection(directionMenu);
      	animationMenu.play();
      	directionMenu = -directionMenu;
    });
    
    // Using Bootstrap Collapse for toggling
    var navLinks = document.querySelectorAll('.nav-link')
    var menuToggle = document.getElementById('lowetoggle')
    var bsCollapse = new bootstrap.Collapse(menuToggle, {toggle:false})
    
    // Event listeners for nav-links
    navLinks.forEach((l) => {
        l.addEventListener('click', () => { 
            if (window.innerWidth < 992){ // Prevent flickering behavior on desktop
                bsCollapse.toggle()
                animationMenu.setDirection(directionMenu);
                animationMenu.play();
                directionMenu = -directionMenu;
            }
         });
});
.navbar-lowe {background-color: black;}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b1d3dedec5c2c5c3d0c1f1849f809f82">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"/>
<nav class="navbar navbar-expand-lg navbar-lowe">
        <div class="container-fluid">
          <a class="navbar-brand" href="#">
            <p>Logo</p>
          </a>
          <button
            class="navbar-toggler"
            type="button"
            data-bs-toggle="collapse"
            data-bs-target="#lowetoggle"
            aria-controls="lowetoggle"
            aria-expanded="false"
            aria-label="Toggle navigation"
          >
          <div class="lowe-menu" style="width: 50px;"></div>
          </button>
          <div class="collapse navbar-collapse" id="lowetoggle">
            <div class="navbar-nav align-items-end">
              <a class="nav-link active" href="#home">Home</a>
              <a class="nav-link" href="#work">Work</a>
              <a class="nav-link" href="#contact">Contact</a>
            </div>
            <div class="navbar-text ms-auto text-end">
              <a class="btn nav-button" role="button">Call Today <strong>05555555 555</strong></a>
            </div>
          </div>
        </div>
      </nav>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.8.1/lottie.min.js"></script>
<script src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97f5f8f8e3e4e3e5f6e7d7a2b9a6b9a4">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is it necessary to decode JSON stringified objects in Vue props?

When passing a stringifyed object via props to a component, it seems like there is an issue with the data transformation. <my-component :filter="stringobject" ></my-component> stringobject = "{"search_text":"(ciCl ...

Preventing a JavaScript timer function from executing multiple times when triggered by an 'in viewport' function

I am trying to create a website feature where a timer starts counting up once a specific div is scrolled into view. However, I am encountering an issue where scrolling away restarts the timer, and I would like the final value that the timer reaches to rema ...

Minimize a pop-up window and navigate to a different webpage

I have created a login/logout form that includes the option to delete my account. When I click the "Sterge cont" button, a pop-up window appears asking if I truly want to delete the account. If I select "NU," the account will not be deleted and the window ...

How can I create a new PHP table using data from an existing table?

I have a table displayed on my website with the code snippet providedview the table image here Here is the code for generating this table: <?php $query = $db->query("SELECT * FROM bit_exchanges ORDER BY id DESC LIMIT 20"); if($query-> ...

Utilizing the Jquery hover feature to reveal or conceal an element

My Hover function is designed to display and hide sub menus when a person hovers on them. The issue I'm facing is that the menu disappears when I move the mouse down towards it. Can someone help me identify what I am doing wrong here? ...

Define default array values in Mongoose schemas using Node.js

My model definition includes: appFeatures: [{ name: String, param : [{ name : String, value : String }] }] I am looking to assign a default value to appFeatures, such as: name: 'feature', para ...

Update class name in React component based on state change

My current setup involves the setting of active and class flags as shown below: constructor(props) { super(props); this.state = {'active': false, 'class': 'album'}; } handleClick(id) { if(this.state.active){ this.s ...

Differences between Arrow function and regular function when used in Array.map()

While working on some JS challenges, I observed that when using arrow functions, the result is as expected. However, when I try the same code with a regular function, it doesn't work. Can someone please explain the difference or point out if there is ...

How can the border of the select element be removed when it is active in select2

After examining the CSS code, I am still unable to locate the specific property that is being applied to the main element. I am currently customizing the select2 library to suit my needs. However, I am stuck in the CSS as I cannot determine which property ...

Is there a way to adjust the size of a table display to ensure that both vertical and horizontal scroll bars are constantly visible?

[edits added below per the request to see code. Edits also added to the original post to clarify the ask - marked in bold] My application features a broad table with the potential for many rows, generated by django-tables2 using the bootstrap5-responsive ...

Update the regular expression pattern to extract nested tags and store them in an array of objects

For my small application, I am working on creating a regex pattern to identify "faux" html tags. The goal is to capture these tags within curly brackets and output them into an array of objects. Below is the code snippet with the current regex pattern: { ...

The returned error object from express does not include the error message

I recently posted a question related to an error issue. I am now wondering if I should have edited that question instead. Regarding the code snippet below: app.use((err, req, res, next) => { res.status(err.status || 500); res.json({ message: e ...

Choosing a group of kids who all share the same element tag

I currently have a situation where I need to display only the first two paragraphs in a div when the page loads, with the remaining paragraphs hidden. I am struggling to achieve this and am seeking guidance on how to do so. In the jsfiddle example provided ...

Unexpected behavior encountered with Angular module dependency injection

Having some difficulty managing dependencies for my node app. Here's the current structure: app.js var app = angular.module('myApp', ['myController', 'myFactory', 'rzModule', 'chart.js', 'myServ ...

Creating a Rails application that dynamically fills a table with data from a

Encountering an issue with Ruby on Rails. I have a "Host Model" that contains a method which has a longer runtime. class Host < ActiveRecord::Base def take-a-while # implement logic here end Attempting to access a page where this method ru ...

Highchart displays results for each individual line without the use of commas

I am interested in creating a chart using Highchart with three lines. The first two lines will display data similar to [4.12, 3.34, 5.45] / [3.45, 5.45, 3.23], while the third line should be displayed without any commas, showing results like [7, 4, 2]. Can ...

What is the best way to choose the member variables in this specific data structure?

I have been assigned the task of retrieving the cities from various countries, but I am unsure of the best approach to do so. How can I easily extract city names like: For example, for USA it would be NYC and SFO. I attempted using the code snippet cityD ...

Refresh the page when the parameter in the URL changes

I'm encountering a small issue that I can't seem to resolve. Currently, I am on the following page: http://example.com:8080/#/user/5ad142e8063ebb0537c5343e There is a link on this page that points to the URL below: http://example.com:8080/#/u ...

What is the best way to merge values in an array based on their keys?

Here is a sample of the data I have: data = [ [ {"name":"cpumhz","data":[[1433856538,0],[1433856598,0]]}, {"name":"mem","data":[[1433856538,13660],[1433856598,13660]]} ], [ {"name":"cpumhz","data":[[1433856538,0],[1433856598,0]]}, {" ...

Managing a high volume of HTTP requests within a React-Redux application

Seeking assistance with my react-redux app project. I have a substantial amount of data that has been divided into smaller files, allowing the user to choose a start and end time range. Upon clicking the "Fetch data" button, I create HTTP request promise ...