The other answers don't take into consideration that the request may not get completed before the page changes, causing the event not to be recorded.
That's the problem with this solution found in other answers:
<a
href="http://example.com"
onclick="ga('send', 'event', {eventAction: 'click', eventCategory: 'Example'})"
>example</a>
Google Analytics documentation does provide a solution to this:
Tracking outbound links and forms can be tricky because most browsers will stop executing JavaScript on the current page once a new page starts to load. One solution to this problem is to set the transport
field to beacon
beacon
transport allows data to be sent asynchronously to a server, even after a page was closed.
Add transport: 'beacon'
, like this:
<a
href="http://example.com"
onclick="ga('send', 'event', {transport: 'beacon', eventAction: 'click', eventCategory: 'Example'})"
>example</a>
Unfortunately, some browsers don't support beacon, including IE 11 (caniuse). To work around this, you could cancel the page navigation, send the request to Google Analytics, wait for its completion, and then launch the page navigation. Fortunately, all the modern major browsers do support it.