javascriptjquerywordpressprettyphoto

Disable keyboard navigation (Wordpress) when PrettyPhoto modal is open


I'm loading jQuery PrettyPhoto from a CDN. I've got this JS to enable post navigation from the keyboard:

  // Add keyboard navigation for the next & previous post buttons
  $(document).keydown(function (e) {
    var url = false;
    if (e.which == 37) { // Left arrow key code
      url = $('a.prev-post').attr('href'); // change to match the pagination link classes in your theme
    } else if (e.which == 39) { // Right arrow key code
      url = $('a.next-post').attr('href');
    }
    if (url) {
      window.location = url;
    }
  });

I'd like to add a boolean to prevent this code from executing when the PP modal is open, but I'm not sure how to go about it. The relevant code in PP is:

// Window/Keyboard events
$(window).unbind('resize.prettyphoto').bind('resize.prettyphoto',function(){ _center_overlay(); _resize_overlay(); });

if(pp_settings.keyboard_shortcuts) {
  $(document).unbind('keydown.prettyphoto').bind('keydown.prettyphoto',function(e){
    if(typeof $pp_pic_holder != 'undefined'){
      if($pp_pic_holder.is(':visible')){
        switch(e.keyCode){
          case 37:
            $.prettyPhoto.changePage('previous');
            e.preventDefault();
            break;
          case 39:
          $.prettyPhoto.changePage('next');
          e.preventDefault();
          break;
          case 27:
          if(!settings.modal)
            $.prettyPhoto.close();
            e.preventDefault();
            break;
        };
        // return false;
      };
    };
  });
};

I know I can do something like this on the post navigation:

  // Add keyboard navigation for the next & previous post buttons

 var canUseArrows = true;
 $(document).keydown(function (e) {
    var url = false;
    if (e.which == 37 && canUseArrows) { // Left arrow key code
      url = $('a.prev-post').attr('href'); // change to match the pagination link classes in your theme
    } else if (e.which == 39 && canUseArrows) { // Right arrow key code
      url = $('a.next-post').attr('href');
    }
    if (url) {
      window.location = url;
    }
  });

But I'm not sure how to hook into the PP function.

Thanks for looking,


Solution

  • It doesn't seem possible to "hook into the PP function"; however, I've tried with the following, and it works for me:

      // Add keyboard navigation for the next & previous post buttons
      $(document).keydown(function (e) {
        var url = false,
          // Check if the modal is open/visible.
          canNavi = ! $('.pp_pic_holder').is(':visible');
        if (canNavi && e.which == 37) { // Left arrow key code
          url = $('a.prev-post').attr('href'); // change to match the pagination link classes in your theme
        } else if (canNavi && e.which == 39) { // Right arrow key code
          url = $('a.next-post').attr('href');
        }
        if (url) {
          window.location = url;
        }
      });