<<<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?>>>
The answer is "yes" if you define "the day a dividend is given" as the day before the ex-dividend date. You can buy a stock the day before the ex-dividend date then sell it on the ex-dividend date and get the dividend.
There are always at least a few days between the ex-dividend date and the date when the dividend payment is made, so if you wait until the payment date to buy the stock you will not get the dividend
<<<Is the legal?>>>
<<<Do people do it?>>>
I am sure there are, but I don't know of anyone who does it. It is not an effective way of making any money. The market is efficient enough to adjust the stock price by the amount of the dividend when the stock goes ex-dividend
For example, assume XYZ announces they will pay a dividend of $1.00 on the common stock on March 1, 2013 and that the ex-dividend date will be February 21, 2013. If the stock closed at $20.00 per share on February 20, 2013 it will open on February 21, 2013 within a couple of pennies of $19.00 a share unless there is news overnight (between the time the market closes on the 20th and the time the market opens on the 21st) which has an impact on the stock price. The investor who tried to make money by owning the shares just long enough to get the dividend will make $1.00 per share from the dividend and lose $1.00 on the stock because he will sell it for $1.00 less than he paid for it. If you include the trading costs (commissions) to buy and sell he will have a loss.