Skip to content

Instantly share code, notes, and snippets.

@duduindo
Created February 21, 2018 19:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duduindo/aa5f81ef8f6437de6c23ce120c0f8a58 to your computer and use it in GitHub Desktop.
Save duduindo/aa5f81ef8f6437de6c23ce120c0f8a58 to your computer and use it in GitHub Desktop.
Simple polyfill of Selection.prototype.containsNode
import $ from 'jquery';
/**
* {Element} Elemento que o browser tentará encontrar dentro da seleção
*
* @return bool
*/
let containsNode = node => {
const selection = document.getSelection();
// Mozilla, Chrome e Edge
return selection.containsNode(node, true);
};
/**
* {Element} Elemento que o browser tentará encontrar dentro da seleção
*
* @about IE11
* @return bool
*/
const polyfill = node => {
const selection = document.getSelection();
const start = selection.anchorNode.parentNode;
const final = selection.focusNode.parentNode;
const rectSelection = selection.getRangeAt(0).getBoundingClientRect();
const rectBlock = node.getBoundingClientRect();
// Verifica se o primeiro elemento selecionado está dentro do texto
if ($(start).closest(node).length) {
return true;
}
// Verifica se o último elemento selecionado está dentro do texto
if ($(final).closest(node).length) {
return true;
}
// Verifica se o selecionado é maior que o texto
if (rectSelection.top < rectBlock.top && rectSelection.height > rectBlock.height) {
return true;
}
return false;
};
/**
* Se o navegador não der suporte ao Selection.containsNode, sobrescreve a função com polyfill
* MDN: https://goo.gl/oXfdVE
*/
if (!('containsNode' in Selection.prototype)) {
containsNode = polyfill;
}
export {
containsNode,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment