How to keep selected/active HTML link color on page refresh?

前端 未结 1 1145
刺人心
刺人心 2021-01-23 05:01

EDIT:

I want to keep selected keep HTML link color on page refresh. I tried other problems that already been answered but didn\'t work

相关标签:
1条回答
  • 2021-01-23 05:30

    Here's the JS which should be triggered on DOM ready:

    $('#col-navigation a').click(function(e){
       e.preventDefault();
       $(".content").hide().filter( $(this).data("target") ).show();
       localStorage.setItem('target', $(this).data("target"));
    });
    var target = localStorage.getItem('target');
    !target || $('.content').hide().filter(target).show();
    

    And here's the HTML; added data- attribute and .content class:

    <div id="col-navigation">
            <ul>
                <li> 
                    <a href="#" data-target="#quizzes"> Quizzes </a>
                </li>
                <li> 
                    <a href="#" data-target="#categories"> Categories </a>
                </li>
                <li> 
                    <a href="#" data-target="#jump"> Jump </a>
                </li>
            </ul>
    </div>
    
    <div id="quizzes" class="content"> 
         Quizzes! <!-- default showed -->
    </div>
    
    <div id="categories" style="display:none" class="content">
         Categories!
    </div>
    
     <div id="jump" style="display:none" class="content">
         Jump!
    </div>
    

    Demo Using localStorage to remember last selected option

    UPDATE

    As for manipulation of the .focus class, some additional JS will suffice. No need to save any additional info in localStorage.

    $('#col-navigation a').click(function(e){
       e.preventDefault();
       $(this).addClass('focus').parent().siblings().find('a').removeClass('focus'); //<<<--THIS
       $(".content").hide().filter( $(this).data("target") ).show();
       localStorage.setItem('target', $(this).data("target"));
    });
    var target = localStorage.getItem('target');
    !target || $('.content').hide().filter(target).show();
    !target || $('a[data-target="' + target + '"]').addClass('focus').parent().siblings().find('a').removeClass('focus'); //<<<-- AND THIS
    

    Updated Demo

    0 讨论(0)
提交回复
热议问题