Nick Else
Nick Else

Reputation: 154

Session Storage and Fade Toggle Issue

So I have a slight issue with a session storage I've made.

Basically I want the session to store the display state whether that is block or none, now this works perfectly if I use toggle on the click function, but I want to use fadeToggle for aesthetics and for some reason it won't store the state any more.

<button class="button">Show / Hide</button>
<div class="content">Content Goes Here</div>
.button {
    background: white;
    border: 2px solid #333;
    font-family: inherit;
    font-size: 16px;
    font-weight: 600;
    padding: 10px 20px;
    width: 100%;
}

.content {
    display: none;
    background: dodgerblue;
    color: white;
    margin-top: 20px;
    padding: 20px;
}
function toggleTest() {
    $(".button").click(function (event) {
         $(".content").stop().fadeToggle();
         sessionStorage.setItem("show-hide", $(".content").css("display"));
    });

    if (sessionStorage.getItem("show-hide")) {
        $(".content").css("display", sessionStorage.getItem("show-hide"));
    }
}

$(document).ready(function () {
    toggleTest();
});

Any suggestions would be awesome as to why this wouldn't work with fadeToggle.

Cheers!

CodePen: https://codepen.io/nickelse/pen/zYOXGjw

Upvotes: 0

Views: 41

Answers (1)

Dhaval Pankhaniya
Dhaval Pankhaniya

Reputation: 1996

it is because fadeToggle uses animation(before the animation finishes the code sessionStorage.setItem("show-hide", $(".content").css("display")); is been already executed) use callback function for the fadeToggle to overcome and it should work fine

attaching working fiddle link

function toggleTest() {
    $(".button").click(function (event) {
         $(".content").stop().fadeToggle(function(){
            sessionStorage.setItem("show-hide", $(".content").css("display"));
         });
         
    });

    if (sessionStorage.getItem("show-hide")) {
        $(".content").css("display", sessionStorage.getItem("show-hide"));
    }
}

$(document).ready(function () {
    toggleTest();
});
.button {
    background: white;
    border: 2px solid #333;
    font-family: inherit;
    font-size: 16px;
    font-weight: 600;
    padding: 10px 20px;
    width: 100%;
}

.content {
    display: none;
    background: dodgerblue;
    color: white;
    margin-top: 20px;
    padding: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="button">Show / Hide</button>
<div class="content">Content Goes Here</div>

Upvotes: 2

Related Questions