claudios claudios - 6 months ago 10
jQuery Question

Save current state after jquery click function

I am trying to hide a button after clicking another button but as when the page refreshed, the hidden button shows up again. I wanted to remain it hidden even if I refresh the page and show it only if I click the show button.
Any help would be much appreciated.

HTML:

<button type="button" class="showhide">Show / Hide</button>
<button type="button" class="link">Link</button>


JS:

$('.showhide').click(function(){
$('.link').hide();
});

Answer

Like @Kartikeya said, use localStorage.

Set it when you click the button. On page load check the value of the localStorage to update the visibility of the button.

$('.showhide').click(function(){
    $('.link').toggle();

    var isVisible = $('.link').is(":visible"); 
    localStorage.setItem('visible', isVisible);
});

// stored in localStorage as string, `toggle` needs boolean
var isVisible = localStorage.getItem('visible') === 'false' ? false : true;
$('.link').toggle(isVisible);

https://jsfiddle.net/undm500w/8/