Search code examples
jquerytogglemousetrap

jquery mousetrap to toggle offcanvas


So I have this code to show my favorites sidebar when clicking "f" on my keyboard:

Mousetrap.bind('f', function () {
    const bsOffcanvas = new bootstrap.Offcanvas('#favorites');
    bsOffcanvas.show();
});

The only problem is, when clicking "f" again, the sidebar doesn't close, it wants to open again, which means, the background just keeps getting darker because the offcanvas keeps being opened. Is there a way to make a "toggle" so when pressing "f" again it closes?


Solution

  • This works:

    const bsOffcanvas = new bootstrap.Offcanvas('#favorites');
    let isOffcanvasShown = false;
    
    bsOffcanvas._element.addEventListener('shown.bs.offcanvas', function ()     {
        isOffcanvasShown = true;
    });
    
    bsOffcanvas._element.addEventListener('hidden.bs.offcanvas', function ()     {
        isOffcanvasShown = false;
    });
    
    Mousetrap.bind('f', function () {
        if (isOffcanvasShown) {
            bsOffcanvas.hide();
        } else {
            bsOffcanvas.show();
        }
    });