Last active
August 29, 2015 14:11
-
-
Save lukealbao/80b900af3092434a24d3 to your computer and use it in GitHub Desktop.
Go-to-line on GitHub code page
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Go to hash location associated with line of code. | |
* Assigning line in the if clause is done because parseInt | |
* returns falsy if its result is NaN. | |
*/ | |
function goToLine(line) { | |
if (line = parseInt(line)) { | |
document.location.hash = "#L" + line; | |
} | |
} | |
/* | |
* Create a text input element. Place it. | |
* Add two keyup listeners: when hitting "Enter", | |
* run the goToLine function; second, blur() the input | |
* on "Esc" key. | |
*/ | |
var lineBox = document.createElement("input"); | |
lineBox.setAttribute("style", | |
"position: fixed;" + | |
"top: 10px;" + | |
"right: 10px"); | |
lineBox.setAttribute("type", "text"); | |
document.body.appendChild(lineBox); | |
lineBox.addEventListener("keyup", function(evt) { | |
var key = evt.keyCode || evt.which; | |
if (key == 13) { | |
goToLine(lineBox.value); | |
evt.target.value = ""; | |
evt.target.blur(); | |
} else if (key == 27) { | |
evt.target.blur(); | |
} | |
}); | |
/* | |
* Here is the culprit. Listen for keyup events, and when | |
* the key is "/", focus on the input box. Problem: after jumping | |
* to a line once, any subsequent attempts populate the input | |
* with the "/" character. When listening for keydown, the problem | |
* is resolved. | |
*/ | |
document.addEventListener("keyup", function(evt) { | |
var key = evt.keyCode || evt.which; | |
if ( key == 191) { | |
evt.preventDefault(); | |
lineBox.focus(); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Drop this code into the console on a GitHub page. Press "/" to bring focus to the input in the top right. Type in a number, hit
Enter
and jump to a specific line of code. If you do it again, and if you're using Chrome, you might see that the "/" is placed in theinput
element.However, if you change the last
eventListener
to listen forkeydown
instead ofkeyup
, you should be able to jump around without having to delete the "/" each time. Strange bug, seems isolated to Chrome.