Skip to content

Commit 6e38b1b

Browse files
Fix copy code button position (alshedivat#1348)
Fix issue alshedivat#1303 by adding a code wrapper outside the code block. Ref: https://stackoverflow.com/questions/60771472/position-a-button-such-that-it-wont-scroll-with-contents
1 parent 9ef19fa commit 6e38b1b

File tree

2 files changed

+17
-15
lines changed

2 files changed

+17
-15
lines changed

_sass/_base.scss

+6-14
Original file line numberDiff line numberDiff line change
@@ -826,31 +826,23 @@ progress::-moz-progress-bar {
826826
height: inherit;
827827
}
828828

829-
pre {
830-
padding: 8px 12px;
829+
/* Copy button */
830+
.code-display-wrapper {
831831
position: relative;
832832

833-
/* Copy code to clipboard button */
834833
.copy {
835834
background: var(--global-card-bg-color);
836835
border-color: var(--global-bg-color);
837836
border-radius: .3rem;
838-
border-style: solid;
837+
border-style: none;
839838
color: var(--global-text-color);
840839
font-size: medium;
841840
opacity: 0;
842841
position: absolute;
843-
right: .25rem;
844-
top: .25rem;
845-
846-
&:active,
847-
&:focus,
848-
&:hover {
849-
color: var(--global-hover-color);
850-
opacity: 1;
851-
}
842+
right: .15rem;
843+
top: .15rem;
852844
}
853-
845+
854846
&:active .copy,
855847
&:focus .copy,
856848
&:hover .copy {

assets/js/copy_code.js

+11-1
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@
22
var codeBlocks = document.querySelectorAll('pre');
33
codeBlocks.forEach(function (codeBlock) {
44
if (codeBlock.querySelector('pre:not(.lineno)') || codeBlock.querySelector('code')) {
5+
// create copy button
56
var copyButton = document.createElement('button');
67
copyButton.className = 'copy';
78
copyButton.type = 'button';
89
copyButton.ariaLabel = 'Copy code to clipboard';
910
copyButton.innerText = 'Copy';
1011
copyButton.innerHTML = '<i class="fas fa-clipboard"></i>';
11-
codeBlock.append(copyButton);
1212

1313
// get code from code block and copy to clipboard
1414
copyButton.addEventListener('click', function () {
@@ -32,5 +32,15 @@ codeBlocks.forEach(function (codeBlock) {
3232
copyButton.innerHTML = '<i class="fas fa-clipboard"></i>';
3333
}, waitFor);
3434
});
35+
36+
// create wrapper div
37+
var wrapper = document.createElement('div');
38+
wrapper.className = 'code-display-wrapper';
39+
40+
// add copy button and code block to wrapper div
41+
const parent = codeBlock.parentElement;
42+
parent.insertBefore(wrapper, codeBlock);
43+
wrapper.append(codeBlock);
44+
wrapper.append(copyButton);
3545
}
3646
});

0 commit comments

Comments
 (0)