Fixing loop for prev and next functions