Prince
Prince

Reputation: 401

How to show a div and the current link active after page reload jquery

I want to show a div and a link active which is clicked after page reload. Initially class active is called to first link and div is hidden.

I checked everything I could think of, but didn't get the solution as my code is not working after page reload.

Please see the html and jquery code:

<div class="sub-cols" style="display:none;">
    <div class="wraper-berkowits">
    <a class="active" href="<?php echo Mage::getBaseUrl() ?>products-for-sale/attachments.html">Attachments</a>
    <a href="<?php echo Mage::getBaseUrl() ?>products-for-sale/removal.html">Removal</a></li>
    <a href="<?php echo Mage::getBaseUrl() ?>products-for-sale/hair-loss-store.html">Hair Loss</a></li>
    <a href="<?php echo Mage::getBaseUrl() ?>products-for-sale/care-maintenance.html">Care &amp; maintenance </a>
    </div>
</div>


jQuery(document).ready(function() {
    jQuery('.menu:first-child').addClass('first'); 

    jQuery('li.last a').click(function() {  
        jQuery('.sub-cols').show();
        return false;
    }); 

    jQuery(".sub-cols a").click(function () {        
        jQuery(this).addClass('active').siblings().removeClass('active'); 

    });
});

Please check the above code and advise me how to get the desired result.

Upvotes: 1

Views: 1087

Answers (1)

nshah143
nshah143

Reputation: 559

As from your comments the question is better understood now As your need is to regain the state of the link even after the page reload. I can provide you the hint of achieving it

There are two ways - 1) you can $_SESSION in php to store the link clicked and can have it display using jquery

2) Using javascript only - use window.localStorage – stores data with no expiration date

When you need to set a variable that should be reflected in the next page(s), use:

var someVarName = "value";
localStorage.setItem("someVarName", someVarName);

In your code you can do something like this

jQuery(".sub-cols a").click(function () {
        localStorage.setItem("someVarName", jQuery(this).text());
        jQuery(this).addClass('active').siblings().removeClass('active');
    });
    jQuery(".sub-cols").show();

And in any page (like when the page has loaded), get it like:

var someVarName = localStorage.getItem("someVarName");

.getItem() will return null or the value stored.

for your example you can use like this

if(localStorage.getItem("someVarName")!=null){
        $('a').filter(function(){
                return this.innerHTML == localStorage.getItem("someVarName"); 
            }).css({background:"#F00"});
    }

I have provided an updated demo - http://jsfiddle.net/bvqnzuwa/3/ To test it click on any link and then reload the page. You will see a background color on the link you clicked even after page reload.

Upvotes: 1

Related Questions