Wordpress Attachment Page Navigate with Keyboard

181 Views Asked by At

I'm using WordPress.

I want to navigate my attachment page with left and right key.

Here is my codes, but not working;

function GoToLocation(url)
  {
    window.location = url;
  }

  Mousetrap.bind("j", function() {
    //alert('j pressed' + document.getElementById("next").href);
    //document.getElementById("next").click();
    window.location=<?php echo $image->next_image_link ?>;
  });
<script src="https://craig.global.ssl.fastly.net/js/rainbow-custom.min.js?39e99"></script>
<script src="https://craig.global.ssl.fastly.net/js/mousetrap/mousetrap.js?bc893"></script>

If I change that

window.location=<?php echo $image->next_image_link ?>;

to this

window.location="http://mylink.com";

script working well. but I can't use WordPress based link (like next_image_link();)

What can I do?

2

There are 2 best solutions below

0
On BEST ANSWER

i did myself,

firstly add this to top

<script src="https://craig.global.ssl.fastly.net/js/rainbow-custom.min.js?39e99"></script>
<script src="https://craig.global.ssl.fastly.net/js/mousetrap/mousetrap.js?bc893"></script>
Then add this script too

function GoToLocation(url)
  {
    window.location = url;
  }
  Mousetrap.bind("right", function() {
document.getElementById('next-page').click();
  });



function GoToLocation(url)
  {
    window.location = url;
  }
  Mousetrap.bind("left", function() {
document.getElementById('prev-page').click();
  });

lastly, put "next-page" , "prev-page" ID to the location of the link tag for example;

<a id="next-page"></a>

or

<a id="prev-page"></a>

So, when you press Left or Right keyboard button, script will work well. See ya

1
On

Replace window.location=<?php echo $image->next_image_link ?>; with window.location="<?php echo $image->next_image_link ?>";. Your string declariation is not valid so it can't work.

PHP doesn't echo link with inverted commas.

Edit: Wordpress doesn't print just the URL. It prints link element. So the solution will be

  1. Binding to existing navigation
  2. Using regex to cut off the htmt syntax

    var element = '<?php echo $image->next_image_link ?>'; window.location = element.match(/href="([^"]*)/)[1];