All what I know on badges comes from this guide.
https://pokemongo.gamepress.gg/gyms
There, they say that you only get the XP once you get kicked from the gym. Although, I also got the impression that sometimes, somehow, your progress bar grows up a little...It might be just a graphical bug. Didn't note the badge color change as you did