remain added class after refresh

I found this fiddle from other questions, and its good to use. The problem is the added class(.active) in button remove when refresh. How can I make it remain even I reload it.

FIDDLE

HTML

<div class="flr-wrap">
<ul>
    <li><a class="button active" data-rel="#content-a" href="#">a button</a></li>
    <li><a class="button" data-rel="#content-b" href="#">b button</a></li>
</ul>

<div class="flr-inner">
    <div class="container" id="content-a">
        AAA
    </div>
    <div class="container" id="content-b">
        BBB
    </div>
</div>

JS

    // set content on click
$('.button').click(function(e) {
    e.preventDefault();
    setContent($(this));
});

// set content on load
$('.button.active').length && setContent($('.button.active'));

function setContent($el) {
    $('.button').removeClass('active');
    $('.container').hide();

    $el.addClass('active');
    $($el.data('rel')).show();
}

Thanks in advance..

38 thoughts on “remain added class after refresh”

  1. Added more details to Arun’s answer.

    Store menu item in local storage after click.

    $('.menu-item').click(function (e) {
        localStorage.setItem('active-menu-item', $(this).attr('href'));
    });
    

    Set active menu item style by adding class ‘active’ and click the item to go to the active page. It is inside $(document).ready() so that it runs after refresh.

    $(document).ready(function () {
        const activeMenuItem = $('.menu-item[href="' + localStorage.getItem('active-menu-item') + '"]').first();
        activeMenuItem && setActiveLink(activeMenuItem);
    });
    
    function setActiveLink($el) {
        $el.addClass('active');
        $el.click();
    }
    
    Reply
  2. You need to store the active state either in the server(if there is a way to do this) or in the client side(you can use web storage)

    To store it in client side

    // set content on click
    $('.button').click(function(e) {
      e.preventDefault();
      setContent($(this));
      localStorage.setItem('active-container', $(this).data('rel'));
    });
    
    // set content on load
    localStorage.getItem('active-container') && setContent($('.button[data-rel="' + localStorage.getItem('active-container') + '"]'));
    
    function setContent($el) {
      $('.button').removeClass('active');
      $('.container').hide();
    
      $el.addClass('active');
      $($el.data('rel')).show();
    }
    
    Reply

Leave a Comment