index.js 780 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. module.exports = function () {
  2. var selection = document.getSelection();
  3. if (!selection.rangeCount) {
  4. return function () {};
  5. }
  6. var active = document.activeElement;
  7. var ranges = [];
  8. for (var i = 0; i < selection.rangeCount; i++) {
  9. ranges.push(selection.getRangeAt(i));
  10. }
  11. switch (active.tagName.toUpperCase()) { // .toUpperCase handles XHTML
  12. case 'INPUT':
  13. case 'TEXTAREA':
  14. active.blur();
  15. break;
  16. default:
  17. active = null;
  18. break;
  19. }
  20. selection.removeAllRanges();
  21. return function () {
  22. selection.type === 'Caret' &&
  23. selection.removeAllRanges();
  24. if (!selection.rangeCount) {
  25. ranges.forEach(function(range) {
  26. selection.addRange(range);
  27. });
  28. }
  29. active &&
  30. active.focus();
  31. };
  32. };