Skip to content

Instantly share code, notes, and snippets.

@fitsum
Last active April 26, 2024 05:20
Show Gist options
  • Save fitsum/34e6eff995bfe4bafc34f67ed2f4d34f to your computer and use it in GitHub Desktop.
Save fitsum/34e6eff995bfe4bafc34f67ed2f4d34f to your computer and use it in GitHub Desktop.
styled output causes linebreaks in Chrome but not Firefox
// FIXME?
document.styleSheets[document.styleSheets.length - 1].addRule("::selection", "background: red; color: pink");
document.addEventListener('selectionchange', e => {
console.clear();
slice = document.getSelection().toString();
if (slice !== "") {
parent = document.getSelection().getRangeAt(0).commonAncestorContainer.textContent;
preSlice = parent.slice(0, parent.indexOf(slice));
postSlice = parent.slice(parent.indexOf(slice) + slice.length, parent.length - 1);
// string = preSlice + slice.toUpperCase() + postSlice;
//
// Firefox ✔️ Chrome ✖️
//
otherStyle = 'font-weight: normal';
sliceStyle = 'font-weight: bold';
string = "%c"+ preSlice + '%c' + slice + '%c' + postSlice;
console.log(string, otherStyle, sliceStyle, otherStyle);
//
// Firefox ✔️ Chrome ✔️
//
// string = preSlice + '{{ ' + slice.toUpperCase() + ' }}' + postSlice;
// console.log(string);
}
})
@fitsum
Copy link
Author

fitsum commented May 12, 2021

maybe use range's container instead of commonAnscestor ... to capture context, eg. ranges that cross paragraphs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment