copylinkaddress.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. var linkAddress = $('<span id="copylAddress" style="display: inline-block;" />');
  2. $('body').append(linkAddress);
  3. // 'Hidden' yet selectable
  4. linkAddress.css({position: 'absolute', left:'-9999em'});
  5. copylLogging = false;
  6. function selectElement(el) {
  7. var range = document.createRange();
  8. console.log(el[0]);
  9. range.selectNodeContents(el[0]);
  10. window.getSelection().addRange(range);
  11. }
  12. function clearLinkAddress() {
  13. if (linkAddress.text()) {
  14. linkAddress.text("");
  15. linkAddress.blur();
  16. if (copylLogging) {
  17. console.log("Cleared linkAddress");
  18. }
  19. window.getSelection().removeAllRanges();
  20. }
  21. if (copylLogging) {
  22. console.log("Current selection: " + window.getSelection().toString());
  23. }
  24. }
  25. $(function() {
  26. $('a').on({
  27. mouseenter: function() {
  28. if(window.getSelection().toString()) {
  29. if (copylLogging) {
  30. console.log("Something is already selected. Copyl backs out.");
  31. }
  32. } else {
  33. if (copylLogging) {
  34. console.log("Nothing is selected. Copyl kicks in.");
  35. }
  36. linkAddress.text($(this).prop('href'));
  37. selectElement(linkAddress);
  38. if (copylLogging) {
  39. console.log("linkAddress: " + linkAddress.text());
  40. }
  41. }
  42. if (copylLogging) {
  43. console.log("Current Selection: " + window.getSelection().toString());
  44. }
  45. },
  46. mouseleave: function() {
  47. if (copylLogging) {
  48. console.log("Leaving link.");
  49. }
  50. clearLinkAddress();
  51. }
  52. });
  53. // Clear linkAddress when user closes or moves away from the page
  54. // Does not work in Chrome 14+
  55. window.onbeforeunload = function() {
  56. if (copylLogging) {
  57. console.log("Leaving page.");
  58. }
  59. clearLinkAddress();
  60. }
  61. });