Why do chameleons move back and forth?
The movement you observed serves two functions:

Imitation of leaves to protect against predators
Improved stereoscopic vision while scanning for their own prey

Imitation of leaves (mimesis)
Chameleons in the wild live in trees and are surrounded by leaves. In order to protect themselves from predators they move forth and back to blend with leaves moving in the wind.
Also note that their torso shape resembles a leaf:

Why do they move like this even when there is no wind and they are not sitting on a tree? I suppose they just follow their instincts. Evolution &quot;did not prepare&quot; them for sitting in a cage. The lack of ability to know when to move and when not was not a evolutionary disadvantage so there was not pressure to get rid of it.
Improved stereoscopic vision
Chameleons are predators that use their tongue to catch prey e.g. grasshoppers. While they are looking for their next target, they scan their surroundings with both eyes independently, i.e. one scans the left hemisphere, the other eye scans the right hemisphere, thus during this time they have no stereoscopic vision.
Moving forth and back helps alleviating this. They can estimate the distance to their distance better through the use of motion parallax (closer objects seem to move more than object further away when we move sideways). Once they found a target they turn in its direction and then use both eyes to focus on it, preparing to shoot out their tongue.
(Disclaimer: I am not a biologist. This is from my own reasoning and the German Wikipedia article about Chameleons)