Refactored JQuery and fixed previous button issue