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

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