custom.js
103 lines
| 1 | /* Email Encoder */ |
| 2 | /*global jQuery, window*/ |
| 3 | jQuery(function ($) { |
| 4 | |
| 5 | 'use strict'; |
| 6 | |
| 7 | // encoding method |
| 8 | function rot13(s) { |
| 9 | // source: http://jsfromhell.com/string/rot13 |
| 10 | return s.replace(/[a-zA-Z]/g, function (c) { |
| 11 | return String.fromCharCode((c <= 'Z' ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26); |
| 12 | }); |
| 13 | } |
| 14 | |
| 15 | /** |
| 16 | * EMAIL RELATED LOGIC |
| 17 | */ |
| 18 | |
| 19 | // fetch email from data attribute |
| 20 | function fetchEmail(el) { |
| 21 | var email = el.getAttribute('data-enc-email'); |
| 22 | |
| 23 | if (!email) { |
| 24 | return null; |
| 25 | } |
| 26 | |
| 27 | // replace [at] sign |
| 28 | email = email.replace(/\[at\]/g, '@'); |
| 29 | |
| 30 | // encode |
| 31 | email = rot13(email); |
| 32 | |
| 33 | return email; |
| 34 | } |
| 35 | |
| 36 | // replace email in title attribute |
| 37 | function parseTitle(el) { |
| 38 | var title = el.getAttribute('title'); |
| 39 | var email = fetchEmail(el); |
| 40 | |
| 41 | if (title && email) { |
| 42 | title = title.replace('{{email}}', email); |
| 43 | el.setAttribute('title', title); |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | // set input value attribute |
| 48 | function setInputValue(el) { |
| 49 | var email = fetchEmail(el); |
| 50 | |
| 51 | if (email) { |
| 52 | el.setAttribute('value', email); |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | // open mailto link |
| 57 | function mailto(el) { |
| 58 | var email = fetchEmail(el); |
| 59 | |
| 60 | if (email) { |
| 61 | window.location.href = 'mailto:' + email; |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | // revert |
| 66 | function revert(el, rtl) { |
| 67 | var email = fetchEmail(el); |
| 68 | |
| 69 | if (email) { |
| 70 | rtl.text(email); |
| 71 | rtl.removeClass('eeb-rtl'); |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | // prepare for copying email |
| 76 | document.addEventListener('copy', function(e){ |
| 77 | $('a[data-enc-email]').each(function () { |
| 78 | var rtl = $(this).find('.eeb-rtl'); |
| 79 | |
| 80 | if (rtl.text()) { |
| 81 | revert(this, rtl); |
| 82 | } |
| 83 | }); |
| 84 | console.log('copy'); |
| 85 | }); |
| 86 | |
| 87 | // set mailto click |
| 88 | $('body').on('click', 'a[data-enc-email]', function () { |
| 89 | mailto(this); |
| 90 | }); |
| 91 | |
| 92 | // parse title attirbute |
| 93 | $('a[data-enc-email]').each(function () { |
| 94 | parseTitle(this); |
| 95 | }); |
| 96 | |
| 97 | // parse input fields |
| 98 | $('input[data-enc-email]').each(function () { |
| 99 | setInputValue(this); |
| 100 | }); |
| 101 | |
| 102 | }); |
| 103 |