Sometimes, the fermented beer will have some Co2 in solution from the fermentation.
When you add the sugar to it, the Co2 is released and it foams up.
If you add the sugar to the bottle first, you will still get foaming as you bottle, but you can stop and come back to top up the bottle once is...