Big EMPin Big EMPin - 1 month ago 8
Javascript Question

Smoother page loading for saved JQuery toggleClass setting

I'm using the following code to utilize JQuery and local storage to store a toggleClass setting for a collapsible div.

<script type="text/javascript">
$(document).ready(function () {
if (typeof (Storage) !== "undefined") {
$('#wrapper').attr('class', localStorage.getItem("wrapper_class"));
}
$("#menu-toggle").click(function () {
$("#wrapper").toggleClass("active");
localStorage.setItem("wrapper_class", $('#wrapper').attr('class'));
});
});
</script>


The code works fine for the most part. However when the page loads, the collapsible div appears regardless, and then collapses if the last setting was set to do so. From my understanding, this happens because the document.ready function waits until all elements are there and are usable. Is there an easy means to set this to where the load will not look so clunky and to have the collapsible div just appear in its proper state?

Answer

This was just a brain lapse on my part. The problem was that JQuery was taking long enough to load so as to cause a visual disturbance. Setting it with the $('#wrapper').attr function wasn't working too well. I took the localStorage retrieval functionality out of this and loaded it before JQuery was imported.

<script type="text/javascript">
    if (typeof (Storage) !== "undefined") {
        var cName = localStorage.getItem("wrapper_class");
        document.getElementById("wrapper").className = cName;
    }
</script>