Can you buy a stock on the day a dividend is given and sell right after?

I was just wondering, can you buy a stock on the day a dividend is given, take the dividend, and then sell the stock straight away?
Is the legal? Do people do it? What is the effect of this in large quantities if it happens
8 answers 8