Edward144
Edward144

Reputation: 487

jQuery - If statement detect page load

I have a function which is designed to automatically hide a sidebar on smaller screens. The sidebar gets hidden by adding an id which affects the sidebar margin. Transitions are used to animate it sliding left.

As I don't want the sidebar to slide off the screen on page load, I have counteracted this by adding a class to remove transitions then remove that class after 0.5s, the length of the transition.

I have the below function running on both page load and window resize. I only want the transitions to be removed on page load so is there a way to use an if statement to detect this.

function setSidebarState() {
    if($(window).width() < 960) {
        $(".wrapper").attr("id", "sidebarClosed");

        //Page load only
        if($(document).ready()) {
        /***if(!$(window).resize()) - this also doesn't work***/
            $(".sidebar, .content").addClass("noTransition");

            setTimeout(function() {
                $(".sidebar, .content").removeClass("noTransition");
            }, 500);
        }
    }
    else {
        $(".wrapper").attr("id", "");
    }
}

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

$(window).resize(function() {  
    setSidebarState();
}); 

The css is simply

.sidebar {
    width: 320px;
    position: fixed;
    height: 100vh;
    background: #333;
}

.content {
    margin-left: 320px;
}

.wrapper#sidebarClosed > .sidebar {
    margin-left: -270px;
}

.wrapper#sidebarClosed > .content {
    margin-left: 50px;
}

Upvotes: 0

Views: 183

Answers (1)

Robin Zigmond
Robin Zigmond

Reputation: 18249

All you need to do is have a Boolean parameter you can pass to the function:

function setSidebarState(pageLoad) {
    if($(window).width() < 960) {
        $(".wrapper").attr("id", "sidebarClosed");

        //Page load only
        if(pageLoad) {
            $(".sidebar, .content").addClass("noTransition");

            setTimeout(function() {
                $(".sidebar, .content").removeClass("noTransition");
            }, 500);
        }
    }
    else {
        $(".wrapper").attr("id", "");
    }
}

$(document).ready(function() {  
    setSidebarState(true);
}); 

$(window).resize(function() {  
    setSidebarState(false);
}); 

Upvotes: 2

Related Questions