var lastscrollvalue;
window.onscroll = function() {
 console.log('scroll');
 var a = $('#messages');
 if (lastscrollvalue == undefined) {
    console.log('first')
    lastscrollvalue = a.scrollTop;
     // sets lastscrollvalue
 } else if (a.scrollTop > lastscrollvalue) {
    console.log('up');
     // downscroll rules will be here
     lastscrollvalue = a.scrollTop;

 } else if (a.scrollTop < lastscrollvalue) {
     console.log('down');
     // upscroll rules will be here
     lastscrollvalue = a.scrollTop;
 }
}