Last active
March 19, 2018 01:48
-
-
Save ZhangChengX/26c2801476fd075d3a86e40664a72422 to your computer and use it in GitHub Desktop.
Getting highlighted/selected text.
This file contains 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
// Selection object | |
//var selection = window.getSelection(); | |
var selection = window.getSelection ? window.getSelection() : document.selection; | |
// Selected plain text | |
var selected_text = selection.toString(); | |
// Range object | |
var range = selection.getRangeAt(0); | |
// DocumentFragment | |
var fragment = range.cloneContents(); | |
// Selected HTML | |
var div_wrapper = document.createElement("div"); | |
div_wrapper.appendChild(fragment); | |
console.log(div_wrapper.innerHTML); | |
// Wrapping the selected text with span | |
var span_wrapper = document.createElement("span"); | |
span_wrapper.setAttribute("class", "selected_text"); | |
range.surroundContents(span_wrapper); | |
// Create a popup box inside the span | |
var popup_box = document.createElement("span"); | |
popup_box.setAttribute('class', 'popup_box'); | |
popup_box.innerHTML = text; | |
if (span_wrapper.innerHTML.length > 0) { | |
span_wrapper.appendChild(popup_box); | |
} | |
// Remove selection | |
if (selection.removeAllRanges) { | |
selection.removeAllRanges(); | |
} else if (selection.empty) { | |
selection.empty(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment