0cfdcefc168d2a161e8c4c3e659efaa5ebc2cea4
[xkcd-keyboard-nav.git] / xkcd_keyboard_nav.user.js
1 /* xkcd keyboard nav - Navigate xkcd with your keyboard
2 *
3 * Copyright (c) 2015-2018 Adrian Iain Lam <me@adrianiainlam.tk>
4 *
5 * This program is free software. It comes without any warranty, to
6 * the extent permitted by applicable law. You can redistribute it
7 * and/or modify it under the terms of the Do What The Fuck You Want
8 * To Public License, Version 2, as published by Sam Hocevar. See
9 * http://www.wtfpl.net/txt/copying/ for more details.
10 *
11 * +---------------+----------------+
12 * | Key | Navigates to |
13 * +---------------+----------------+
14 * | [right arrow] | next comic |
15 * | [left arrow] | previous comic |
16 * | [f] | first comic |
17 * | [l] | last comic |
18 * | [r] | random comic |
19 * +---------------+----------------+
20 *
21 * This script uses keyboardEvent.key, which may not be supported by
22 * your browser. I have no intention to write a compatible script
23 * with keyboardEvent.keyCode as it is deprecated anyway.
24 */
25
26 // ==UserScript==
27 // @name xkcd keyboard nav
28 // @namespace https://github.com/adrianiainlam
29 // @description Navigate xkcd with your keyboard
30 // @version 1.0.4
31 // @downloadURL https://gist.github.com/adrianiainlam/542dd0794a874ca31321/raw/xkcd_keyboard_nav.user.js
32 // @updateURL https://gist.github.com/adrianiainlam/542dd0794a874ca31321/raw/xkcd_keyboard_nav.user.js
33 // @include /^https?://xkcd\.com(/[0-9]+)?/?$/
34 // @grant none
35 // ==/UserScript==
36
37 function showTitleText() {
38 var elem = document.getElementById("comic");
39 var child = elem.children[0];
40 var newnode = document.createElement("p");
41 if(child instanceof HTMLImageElement) {
42 newnode.appendChild(document.createTextNode(child.title));
43 } else if(child instanceof HTMLAnchorElement && child.children[0] instanceof HTMLImageElement) {
44 newnode.appendChild(document.createTextNode(child.children[0].title));
45 } else {
46 console.log("Title text not found by this script. Please file a bug report with URL");
47 }
48 elem.appendChild(newnode);
49 }
50
51 document.body.addEventListener("keypress", function(e) {
52 if (!(e.target instanceof HTMLBodyElement)) {
53 return;
54 }
55 var navList = document.getElementsByClassName("comicNav")[0].children;
56 if(!e.altKey && !e.ctrlKey && !e.metaKey && !e.shiftKey) {
57 switch(e.key) {
58 case "ArrowLeft": // prev
59 document.location.href = navList[1].firstChild.getAttribute("href");
60 break;
61 case "ArrowRight": // next
62 document.location.href = navList[3].firstChild.getAttribute("href");
63 break;
64 case "r": // random
65 document.location.href = navList[2].firstChild.getAttribute("href");
66 break;
67 case "f": // first
68 document.location.href = navList[0].firstChild.getAttribute("href");
69 break;
70 case "l": // last
71 document.location.href = navList[4].firstChild.getAttribute("href");
72 break;
73 }
74 }
75 });
76
77 showTitleText();