Created
January 31, 2020 08:31
-
-
Save marcelblijleven/79235e0597955a54e99f0050c1d5561b to your computer and use it in GitHub Desktop.
Text selections through JS
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
// Url to test on: https://the-internet.herokuapp.com/tinymce | |
function selectorTest() { | |
const iframeDocument = document.querySelector('iframe').contentDocument | |
const textNode = iframeDocument.querySelector('#tinymce p') | |
const text = textNode.firstChild | |
let selection = iframeDocument.getSelection() | |
// Remove all existing ranges first | |
selection.removeAllRanges() | |
// Create a range based on the firstChild (text) of the <p> element | |
const startPos = Math.round(text.length / 2) | |
const endPos = startPos + 2 | |
const range = iframeDocument.createRange() | |
range.setStart(text, startPos) | |
range.setEnd(text, endPos) | |
selection.addRange(range) | |
// Do some selection edits | |
let cursor = startPos | |
let interval = setInterval(function() { | |
if (cursor === endPos) { | |
clearInterval(interval) | |
} | |
selection.modify('extend', 'forward', 'character') | |
cursor += 1 | |
}, 1000) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment