diff options
| author | Teddy Wing | 2017-09-29 00:22:45 +0200 |
|---|---|---|
| committer | Teddy Wing | 2017-09-29 00:56:13 +0200 |
| commit | 6e9040f7ef45ef8262cdbebab719cd961c5b1147 (patch) | |
| tree | 43543915e052d66e2b3d845cb2103d643191da7c /github-apple-option-p-to-preview.user.js | |
| parent | a56fc2cdc16929216bea1db71b76641152a9c00b (diff) | |
| download | GitHub-Apple-Option-P-to-Preview-6e9040f7ef45ef8262cdbebab719cd961c5b1147.tar.bz2 | |
Enable listener for all comment fields including future ones
The keyboard shortcut now works on all comment fields, including those
that are created after page load.
Thanks to this Stack Overflow answer from 'adeneo' and Suraj Jain:
https://stackoverflow.com/questions/20330945/how-to-addeventlistener-to-future-dom-elements/20331016#20331016
It takes advantage of the fact that JavaScript events bubble. We attach
an event to `<body>`, which we can be sure will always be there (even
across GitHub's Turbolinks), and in the keydown event listener check to
see whether we were called on the right element.
Diffstat (limited to 'github-apple-option-p-to-preview.user.js')
| -rw-r--r-- | github-apple-option-p-to-preview.user.js | 20 |
1 files changed, 13 insertions, 7 deletions
diff --git a/github-apple-option-p-to-preview.user.js b/github-apple-option-p-to-preview.user.js index 72e40a4..c6eac52 100644 --- a/github-apple-option-p-to-preview.user.js +++ b/github-apple-option-p-to-preview.user.js @@ -10,22 +10,28 @@ var KEY_CODE_P = 80; -var comment_textareas = document.querySelectorAll('textarea.js-comment-field'); +document.body.addEventListener( + 'keydown', + function(e) { + var node = e.target; + + if (node.type !== 'textarea' || + node.className.indexOf('js-comment-field') === -1) { + return; + } -for (var i = 0; i < comment_textareas.length; i++) { - comment_textareas[i].onkeydown = function(e) { if (e.metaKey && e.altKey && e.keyCode == KEY_CODE_P) { - show_preview_pane(this); + show_preview_pane(node); - var write_tab = this + var write_tab = node .closest('.js-previewable-comment-form') .querySelector('.js-write-tab'); window.setTimeout(function() { register_pane_toggle_shortcut(write_tab); }); } - }; -} + } +); function show_preview_pane (node) { |
