JSFiddle - React, Tailwind, and code Playground

by BramVanroy

HTML

<div>http://www.theinternet.com/an-article#img-1</div>

JavaScript

function navigateLightbox(direction) {
    var loc = $("div").text(),
        locstr = loc.match(/#img-\d+/),
        digit = loc.split("-").pop(),
        locnext = locstr.replace(/(#img-)(\d+)/, function ($0, $1, $2) {
            return $1 + (Number($2) + 1);
        }),
        locprev = locstr.replace(/(#img-)(\d+)/, function ($0, $1, $2) {
            return $1 + (Number($2) - 1);
        });
    console.log(digit);    
    if (direction == "left" && digit > "1") {
        $("div").text(locprev);
    } else if (direction == "right" && digit < "10") {
        $("div").text(locnext);
    } else if (direction == "esc" && digit < "10") {
        // nope
    }
}

$(document).keydown(function (e) {
    console.log("triggered");
    switch (e.which) {
        case 37:
            //left
            navigateLightbox("left");
            break;

        case 39:
            // right
            navigateLightbox("right");
            break;

        case 27:
            // esc
            navigateLightbox("esc");
            break;

        default:
            return; // exit this handler for other keys
    }
    e.preventDefault();
});