The code in the example that Jan provided is explained here:
In essence, the mouse can move further than the boundary of your stimulus within one screen refresh, so it isn’t reliable to keep testing if the mouse is pressed within the stimulus. Instead, after the first time the mouse is pressed within a stimulus, you set a flag to indicate that a drag is under way, and just keep updating the stimulus position to match the mouse, until the mouse button is released.