With thanks to GreenJello on #javascript