Static Header Bar and restore window position after action

Nice if you scrolling and your header stays on top and keep your window position after ajax

by Konstantin Heinrich

HTML

<div id="topToolbar" class="header">
     <h1>This is a nice header</h1>

    <button id="fireAjax">Send somethink</button>
</div>
<div id="content"></div>

CSS

.header {
    background-color:transparent;
    width:100%;
    height:120px;
}

.staticHeaderBar {
    background-color:lightblue;
    position:fixed;
    top:0px;
    width: 100%;
   
}
.sometext {
    margin-bottom:-10px;
    text-align:center;
}

JavaScript

//Create some content to scroll
for (var i = 0; i < 40; i++) {
    $('#content').append('<p class="sometext">scroll to bottom</p>');

}


//Keep the Header on top
var element = $("#topToolbar");
var pos = element.position();
$(window).scroll(function () {
    var windowpos = $(window).scrollTop();
    if (windowpos >= pos.top) {
        element.addClass("staticHeaderBar");
    } else {
        element.removeClass("staticHeaderBar");
        
    }
});

//After ajax it will be aut. scroll to your windowposition befor ajax send
$('#fireAjax').click(function () {
    var actualWindowPos = $(window).scrollTop();
    $.ajax({
        url: '/echo/json/',
        dataType: "json",
        type: 'post',
        
        traditional: true,
        success: function (data) {
            //Will restore your position
            window.scrollTo(0, actualWindowPos) //0 => left | actualWindowPos => height
            alert(data + " windowPosition: " + actualWindowPos);
        }
    });
});