shorten.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. //wrap everything in a self-executing anonymous function to avoid conflicts
  2. (function(){
  3. // smart(x) from Paul Irish
  4. // http://paulirish.com/2009/throttled-smartresize-jquery-event-handler/
  5. (function($,sr){
  6. // debouncing function from John Hann
  7. // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
  8. var debounce = function (func, threshold, execAsap) {
  9. var timeout;
  10. return function debounced () {
  11. var obj = this, args = arguments;
  12. function delayed () {
  13. if (!execAsap)
  14. func.apply(obj, args);
  15. timeout = null;
  16. };
  17. if (timeout)
  18. clearTimeout(timeout);
  19. else if (execAsap)
  20. func.apply(obj, args);
  21. timeout = setTimeout(delayed, threshold || 100);
  22. };
  23. }
  24. jQuery.fn[sr] = function(fn){ return fn ? this.bind('keypress', debounce(fn, 1000)) : this.trigger(sr); };
  25. })(jQuery,'smartkeypress');
  26. function longestWordInString(string)
  27. {
  28. var words = string.split(/\s/);
  29. var longestWord = 0;
  30. for(var i=0;i<words.length;i++)
  31. if(words[i].length > longestWord) longestWord = words[i].length;
  32. return longestWord;
  33. }
  34. function shorten()
  35. {
  36. var $noticeDataText = $('#'+SN.C.S.NoticeDataText);
  37. var noticeText = $noticeDataText.val();
  38. if(noticeText.length > maxNoticeLength || longestWordInString(noticeText) > maxUrlLength) {
  39. var original = $noticeDataText.val();
  40. shortenAjax = $.ajax({
  41. url: $('address .url')[0].href+'/plugins/ClientSideShorten/shorten',
  42. data: { text: $noticeDataText.val() },
  43. dataType: 'text',
  44. success: function(data) {
  45. if(original == $noticeDataText.val()) {
  46. $noticeDataText.val(data).keyup();
  47. }
  48. }
  49. });
  50. }
  51. }
  52. $(document).ready(function(){
  53. $noticeDataText = $('#'+SN.C.S.NoticeDataText);
  54. $noticeDataText.smartkeypress(function(e){
  55. //if(typeof(shortenAjax) !== 'undefined') shortenAjax.abort();
  56. if(e.charCode == '32') {
  57. shorten();
  58. }
  59. });
  60. $noticeDataText.bind('paste', function() {
  61. //if(typeof(shortenAjax) !== 'undefined') shortenAjax.abort();
  62. setTimeout(shorten,1);
  63. });
  64. });
  65. })();