Place Active class in a dynamic menu with Javascript

Asked

Viewed 502 times

1

I created a menu-controller.js file, which is responsible for taking the menu in my API and dynamically generating in my HTML pages I want to use it.

However, I need that when the user clicks on some menu option, it gets the effect of CSS :active. Could someone explain to me how I can do this?

menu-controller.js

const MenuController = (function () {

    let integration = new MenuIntegration({});

    const menu = function() {

        return sessionStorage.getItem("menu");

    };

    const init = function () {

        if (!menu()) {

            const menuArr = integration.getMenu();
            sessionStorage.setItem("menu", percorreMenu(menuArr));

        }

        $(".main-menu").html(menu());
    }

    function percorreMenu (menuArr)  {
        var menu = ""; 
        for (i = 0; i < menuArr.length; i++){
            let menuItem =  menuArr[i];
            menu += 
            `<li class="item-menu active">
                    <a href="${menuItem.link}"><i class="zmdi ${menuItem.icon}"></i> ${menuItem.label}</a>
            </li>`;   
        }

        $('.item-menu').click(function(e) {
            $('.item-menu').removeClass('active');
            $(this).addClass('active');
          });

          // verificar via JS:
          const href = [location.pathname, location.search].join('?');
          $('.item-menu[href="' + href + '"]').addClass('active');

        return menu;

    }

    return {
        init: init
    }

})();

$(document).ready(function () {
    MenuController.init();
});
  • :active is a pseudo-class, you cannot apply it to an element. As well as : hover, is activated from an event, a click for example. In your code, you are adding and removing a class called "active", which is perfect, just put the desired style in this class

  • You have to make a CSS for the ". active" type .active {color:red} the :active is the state of the element when it is being pressed with the mouse, and ". active" is just a name for the class you will add to the element, and its style needs to be built in CSS,

  • Thanks guys, I got it fixed!!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.