For some reason I decided to port a snippet from AS3 to JS. Chose this one:
http://actionsnippet.com/?p=2969#comment-5674
…pretty much at random.
Here is the port in a pen:
This is actually a port of a port from this old thread:
http://www.gamedev.net/topic/444154-closest-point-on-a-line/