JQuery and Cookie: How to remove them when user leaves the page or exit window/tab

cookies, html, javascript, jquery

Solution

$(window).on('beforeunload', function () {
    // Remove the cookie
    $.cookie("name_of_cookie", null);
});

Also, we have one more option:

$(window).unload(function () {
    // Remove the cookie
    $.cookie("name_of_cookie", null);
});

Problem

I am learning to use this JQuery cookie plugin at https://github.com/carhartl/jquery-cookie From what I have read, it's really easy to read and remove a cookie. My question is: I want the cookie to be removed when the user navigates away from the page or close the window/tab, how do I do that? How do I detect such activity? Thanks.

Original source