JVG
JVG

Reputation: 21170

Using a callback to disable a jquery script

I'm using a script to make a user's keyboard control left/right slide navigation on a webpage. Here's the script:

$(document.documentElement).keyup(function (event) {
        // handle cursor keys
        if (event.keyCode == 37) {
            // go left
            $('.leftArrow').click(); // triggers a click on the 'prev' span
        } else if (event.keyCode == 39) {
            // go right
            $('.rightArrow').click(); // triggers a click on the 'next' span
        }
    }); 

However, I'm also using FancyBox (a jquery lightbox plugin), which uses left/right arrows to control the images in the lightbox. The script allows callbacks (see the documentation in the link).

When the lightbox is activated, I'd like to disable the script; then when the lightbox is un-loaded, I'd like to reactivate the code above. Is this possible?

Upvotes: 0

Views: 197

Answers (2)

dfsq
dfsq

Reputation: 193301

The simplest is to check inside your handler if fancybox gallery is active:

$(document.documentElement).keyup(function(event) {

    if ($('#fancybox-overlay').length) {
        return false;
    }

    // handle cursor keys
    if (event.keyCode == 37) {
        // go left
        $('.leftArrow').click(); // triggers a click on the 'prev' span
    } else if (event.keyCode == 39) {
        // go right
        $('.rightArrow').click(); // triggers a click on the 'next' span
    }
}); 

Upvotes: 2

Anders Arpi
Anders Arpi

Reputation: 8417

You can use .off() to remove an event handler from an object: http://api.jquery.com/off/

However since this should be working only under certain conditions (so, turned on and off) I think you should create some check in the keyup event, like:

$(document.documentElement).keyup(function (event) {
    //check that fancybox isnt active
    //could use a custom attribute like data-active to set this as well,
    //or some other variable
    if($(myFancyBox).css("display") != "none") {
        // handle cursor keys
        if (event.keyCode == 37) {
            // go left
            $('.leftArrow').click(); // triggers a click on the 'prev' span
        } else if (event.keyCode == 39) {
            // go right
            $('.rightArrow').click(); // triggers a click on the 'next' span
        }
    }
}); 

Upvotes: 1

Related Questions