Jquery Twitter Like character offset for shortened links

Hi, I'm trying to emulate a character counter on Twitter. Therefore, when you enter or insert a restriction, it decreases. But the service I'm writing for this will also have a shortened URL, so I want to compensate for it with the number of characters that the final URL will be. Shortening occurs at the end of the publication, and not when entering the URL.

Almost everything works for me, but when I click on an element, the offset no longer exists, and the number of characters returns to what it would be if the links were their full length. I believe this is because I use the .change () method, not the .bind ("insertion"), but the input paste did not apply the offset.

/* Character Count for Posts */ function checkPostForURL(post){ var matches = [], urlexp = new RegExp("(^|[ \t\r\n])((http|https):(([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]))","g"), $linkShort = $('#linkstoshort'), matchIdx = 0; if ( post !== undefined ){ if ( urlexp.test(post) ){ var offset = 0; $('.shortenlinks').show(); matches = post.match(urlexp); $linkShort.html(''); for(; matchIdx < matches.length; matchIdx++) { var match = matches[matchIdx], matchOffset = match.length - 23; offset += matchOffset; $linkShort.append('<li>'+match+'</li>'); } return offset; } } } $(function(){ var $postMsg = $('#post-msg'), message = $postMsg.text(), twstartchars = 140 - message.length, fbstartchars = 420 - message.length, $fbCount = $("#fb-char"), $twCount = $("#tw-char"), setRemainingChars = function (evt) { var a = $postMsg.val().length, post = $postMsg.val(); var offset = checkPostForURL(post); if ( offset ){ a = a - offset; } $fbCount.text((420-a)); $twCount.text((140-a)); if ( a > 120 ){ $fbCount.css('color','red'); if ( a > 380 ){ $fbCount.css('color','red'); } }else{ $fbCount.css('color','#333'); $twCount.css('color','#333'); } }; $fbCount.text(fbstartchars); $twCount.text(twstartchars); $postMsg.on('keypress change', setRemainingChars); }); 

UPDATE: I made a JS script to better demonstrate what I'm trying to do http://jsfiddle.net/FUADn/384/

+4
source share
1 answer

Have you tried to bind the .keyup () event on the input instead of the change event? This should technically work and retain binding after using the bridge, etc.

0
source

Source: https://habr.com/ru/post/1383669/


All Articles