Dogs wag their tails when they are happy as a way to communicate their emotions and to show their excitement and joy. The wagging of a dog's tail is a form of body language that can express a range of emotions, such as happiness, excitement, and friendliness. It is a natural behavior for dogs to wag their tails when they are feeling positive emotions and want to interact with others.