Search code examples
javascriptjquerynode.jspughref

How to make my .selected class stay on the correct a(href) after the reload in a list of hrefs


I have a sidebar of links that loads everytime you click on a link, however when I load the next page, the .selected class moves back to "all" instead of the selected link.

I know this is explained with tabs on here but I could not make it work using the methods I found with my list instead of tabs

I am using javascript to compile the list of links, jade for display.

Jade Code(Kinda, I deleted the unnecessary stuff)

        ul.new.category
          li.selected
            div
              a.anm_det_pop(href='/popular')
                strong All
          each i in list
            li
              div
                a.anm_det_pop(href='/page/#{i}')
                  strong #{i.toUpperCase()}

My Script

script.
$(function(){
  $('.category > li').click(function(){
    $('.category > li').removeClass('selected');
    $(this).addClass('selected');
  });
});

The script works to the point where I click it I briefly see the class switch before the reload, after the reload the .selected class goes back to all.

What I would like to accomplish is the .selected class staying on the active link.

Any help would be greatly appreciated. Thanks!


Solution

  • Figured it out, for those with the same question, I moved the whole function into a mixin, I had already made the function in js with sequilize to include the current page as well as the list for my href list so it was relatively simple.

    mixin List(List,currentPage)
      ul.new.category
        li(class=!currentPage ? 'selected' : '')
          div
            a.anm_det_pop(href='/popular')
              strong All
        each i in list
          li(class=currentPage === i.page ? 'selected' : '')
            div
              a.anm_det_pop(href='/genre/#{i.page}')
                strong #{toTitleCase(i)}
    

    Than in the Jade you just add the mixin and than add the list as a param

    +List(List,currentPage)
    

    The mixin reads the current page and compares it to the list, than makes that selection in the list have the class .selection.

    Perfect for what I needed.

    Hope this helps someone else out as I spent a day tryin to figure out something that took me 15 minutes to do