cursor management in element


/ Published in: Other
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <div id="area" style="width:300px;height:300px;" onblur="onDivBlur();" onmousedown="return cancelEvent(event);" onclick="return cancelEvent(event);" contentEditable="true" onmouseup="saveSelection();" onkeyup="saveSelection();" onfocus="restoreSelection();"></div>
  2. <script type="text/javascript">
  3. var savedRange,isInFocus;
  4. function saveSelection()
  5. {
  6. if(window.getSelection)//non IE Browsers
  7. {
  8. savedRange = window.getSelection().getRangeAt(0);
  9. }
  10. else if(document.selection)//IE
  11. {
  12. savedRange = document.selection.createRange();
  13. }
  14. }
  15.  
  16. function restoreSelection()
  17. {
  18. isInFocus = true;
  19. document.getElementById("area").focus();
  20. if (savedRange != null) {
  21. if (window.getSelection)//non IE and there is already a selection
  22. {
  23. var s = window.getSelection();
  24. if (s.rangeCount > 0)
  25. s.removeAllRanges();
  26. s.addRange(savedRange);
  27. }
  28. else
  29. if (document.createRange)//non IE and no selection
  30. {
  31. window.getSelection().addRange(savedRange);
  32. }
  33. else
  34. if (document.selection)//IE
  35. {
  36. savedRange.select();
  37. }
  38. }
  39. }
  40. //this part onwards is only needed if you want to restore selection onclick
  41. var isInFocus = false;
  42. function onDivBlur()
  43. {
  44. isInFocus = false;
  45. }
  46.  
  47. function cancelEvent(e)
  48. {
  49. if (isInFocus == false && savedRange != null) {
  50. if (e && e.preventDefault) {
  51. //alert("FF");
  52. e.stopPropagation(); // DOM style (return false doesn't always work in FF)
  53. e.preventDefault();
  54. }
  55. else {
  56. window.event.cancelBubble = true;//IE stopPropagation
  57. }
  58. restoreSelection();
  59. return false; // false = IE style
  60. }
  61. }
  62. </script>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.