I have a text area where I do a countdown on .keyup() but it although it does what it supposed to it lets the user to believe that there id 1 character left to type, yet the length of the text area has reached the limit. Here is my code:
<script>
var w_limit = 3000;
$(document).ready(function(){
$('#comment').keyup(function(e) {
el = $(this);
if(el.val().length >= w_limit){
el.val( el.val().substr(0, w_limit) );
} else {
$("#word-count").text(w_limit-el.val().length + ' characters left');
}
});
});
</script>
Aside from your typos, you need to always run the $("#word-count").text(stuff); part. Here's it working without the else:
var w_limit = 20;
$(document).ready(function () {
$('#comment').keyup(function (e) {
var el = $(this),
val = el.val();
if (val.length >= w_limit){
el.val( val.substr(0, w_limit) );
}
$("#word-count").text(w_limit - el.val().length + ' characters left');
});
});
DEMO: http://jsfiddle.net/eHstm/
(of course, I used a lower w_limit number for testing purposes)
Related
type in textarea..on textarea change it updates counter of "char_count" once it reaches at 0 it blinks..then hit backspace till counter reaches at 1
the issue is it wont stop blinking
<div>
<textarea rows="10"></textarea>
<div class="char_count">5 characters remaining</div>
</div>
here is jsfiddle
https://jsfiddle.net/mzx79os2/1/
I have looked into the fiddle you've attached. There are two issues,
On keyup you're attaching jQuery animations each time on keyup. So clearing the interval wont help you.
jQuery animation has to be stopped, use $(element).stop(true, true)
I have updated the jsFiddle and also added a check isBlinking to attach animation only once.
Check this link
https://jsfiddle.net/mzx79os2/8/
var descriptionTextarea = $("textarea");
var char_count = ".char_count";
var textMax = 5;
var isRunning = false;
var clearInt = 0;
$(char_count).html(textMax + ' characters remaining');
descriptionTextarea.on("keyup", function(e) {
e.stopPropagation();
var textLength = $(this).val().length;
var textRemaining = textMax - textLength;
var selfCharCounter = $(this).parent().find(char_count);
function blink() {
$(selfCharCounter).fadeOut(500).fadeIn(500);
};
if (textRemaining <= 0 && !isRunning) {
selfCharCounter.css("color", "red");
clearInt = setInterval(blink, 500);
isRunning = true;
} else if (textRemaining > 0 && isRunning) {
isRunning = false;
selfCharCounter.css("color", "");
$(selfCharCounter).stop(true, true).fadeOut();
$(selfCharCounter).stop(true, true).fadeIn()
clearInterval(clearInt);
clearInt = 0;
}
selfCharCounter.html(textRemaining + ' characters remaining');
});
There are multiple problems with your code:
In your case clearInt is set inside the keyup handler (so after every keypress you reset clearint to 0 so you don't clear the right one)
You set multiple intervals on every keypress and you just remove the last one, you should only add an interval if there's not one already running
To stop the animation you should use the stop method of jQuery
You should also paste the code with the problem on SO
https://jsfiddle.net/mzx79os2/13/
var $descriptionTextarea = $("textarea");
var $char_count = $(".char_count");
var textMax = 5;
var animation, animationInProcess;
$char_count.html(textMax + ' characters remaining');
function blinkStart(selfCharCounter) {
console.log('run blink');
animationInProcess = true;
animation = setInterval(function(selfCharCounter){
if( !animationInProcess){
blinkStop(selfCharCounter)
return;
}
$(selfCharCounter).fadeOut(500).fadeIn(500);
}, 500, selfCharCounter);
};
function blinkStop(selfCharCounter){
console.log('stop blink');
$(selfCharCounter).stop(true, true).show();
clearInterval(animation);
};
$descriptionTextarea.on("keyup",function(e){
e.stopPropagation();
var textLength = $(this).val().length;
var textRemaining = textMax - textLength;
var selfCharCounter = $(this).next();
if(textRemaining <= 0){
(!animationInProcess) && blinkStart(selfCharCounter);
selfCharCounter.css("color","red");
}else{
animationInProcess = false;
selfCharCounter.css("color","");
}
selfCharCounter.html(textRemaining + ' characters remaining');
});
I have a text and I want to dynamically shortened the text with “Read More” link using JavaScript. I use the following JavaScript code:
var limitDesc = -1;
function ResponsiveDesc() {
//var limitDesc = 100;
//var isHTML = RegExp.prototype.test.bind(/(<([^>]+)>)/i);
var chars = $("#ResponsiveDescription").html();
if (chars.length > limitDesc) {
var visiblePart = $("<span> " + chars.substr(0, limitDesc - 1) + " </span>");
var dots = $("<span class='dots'>... </span>");
var hiddenPart = $("<span class='more'>" + chars.substr(limitDesc - 1) + "</span>");
var readMore = $("<span class='read-more'>More</span>");
readMore.click(function () {
$(this).prev().remove(); // remove dots
$(this).next().show(); //show hiddenPart
$(this).remove(); // remove readMore
});
$("#ResponsiveDescription").empty()
.append(visiblePart)
.append(dots)
.append(readMore)
.append(hiddenPart);
}
}
$(document).ready(function () {
if (limitDesc > 0 && $(window).width() < 500) {
ResponsiveDesc();
}
});
The main problem is that I don't what this code to cut my text in the middle of a word or a link. What is the best way to solve this problem ?
I can manually change the "limitDesc" variable on each page but when the content of the page is dynamic, it's impossible.
Thanks you in advance.
You can split the string at the last whitespace before your length limit.
You can determine it using lastIndexOf():
limitDesc = chars.lastIndexOf(" ", limitDesc);
http://www.w3schools.com/jsref/jsref_lastindexof.asp
I have these code for making a typing script inside the textarea placeholder.It works fine.But I need to execute the typeIt function When I scroll to the form div.
var txt = "Function will execute when scrolling to the section";
var modified_txt = "";
function humanize() {
return Math.round(Math.random() * (200 - 30)) + 30;
}
//Delete final character in modified string
function deleteCharacter(text) {
//return everything but the last character
text = text.substring(0, text.length - 1);
return text;
}
//Insert character_added at end of text
function addCharacter(text, character_added) {
text = text + character_added;
return text;
}
//typos[char].error is just a self reference, it is not used
var typos = {
}
var timeOut;
var txtLen = txt.length;
var char = 0;
$('textarea').attr('placeholder', '|');
function typeIt() {
modified_txt += txt.charAt(char);
$('textarea').attr('placeholder', modified_txt + '|');
if (char === txtLen) {
$('textarea').attr('placeholder', $('textarea').attr('placeholder').slice(0, -1)); // remove the '|'
return; //Stop the loop once text is completely written.
}
var test = typos[char];
if (test !== undefined) {
setTimeout(function () {
var chunk_one = test.correction(modified_txt);
modified_txt = chunk_one;
char++;
typeIt();
}, humanize());
}
//If no typos are found then move to the next character
else {
setTimeout(function () {
char++;
typeIt();
}, humanize());
}
}
$(function () {
typeIt();
});//end jquery
You can use it this way (example with your codebase):
<div>1</div>
<div>1</div>
<div>1</div>
<div>1</div>
<div>1</div>
<div id="2">2</div>
<div>2</div>
<div>2</div>
<div>2</div>
<script>
var oTop = $('#2').offset().top - window.innerHeight;
$(window).scroll(function () {
var pTop = $('body').scrollTop();
console.log(pTop + ' - ' + oTop); //just for your debugging
if (pTop > oTop) {
alert();
}
});
function humanize() {
return Math.round(Math.random() * (200 - 30)) + 30;
}
//Delete final character in modified string
function deleteCharacter(text) {
//return everything but the last character
text = text.substring(0, text.length - 1);
return text;
}
//Insert character_added at end of text
function addCharacter(text, character_added) {
text = text + character_added;
return text;
}
//typos[char].error is just a self reference, it is not used
var typos = {
}
var timeOut;
var txtLen = txt.length;
var char = 0;
$('textarea').attr('placeholder', '|');
function typeIt() {
modified_txt += txt.charAt(char);
$('textarea').attr('placeholder', modified_txt + '|');
if (char === txtLen) {
$('textarea').attr('placeholder', $('textarea').attr('placeholder').slice(0, -1)); // remove the '|'
return; //Stop the loop once text is completely written.
}
var test = typos[char];
if (test !== undefined) {
setTimeout(function () {
var chunk_one = test.correction(modified_txt);
modified_txt = chunk_one;
char++;
typeIt();
}, humanize());
}
//If no typos are found then move to the next character
else {
setTimeout(function () {
char++;
typeIt();
}, humanize());
}
}
$(function () {
typeIt();
});//end jquery
</script>
You need to capture and assign a event handler to the scroll event.
for demostration purpose i have taken a div with some dummy data
HTML content
<div id="scrollDiv" style="width:50px;height:50px;overflow:scroll;" >We've Worked For a lot of people and of course we've made them so happy! You can read some handpicked Word about us here We've Worked For a lot of people and of course we've made them so happy! You can read some handpicked Word about us here
We've Worked For a lot of people and of course we've made them so happy! You can read some handpicked Word about us here We've Worked For a lot of people and of course we've made them so happy! You can read some handpicked Word about us here</div>
Jquery
$('#scrollDiv').scroll(function(){
alert('scrolling');
});
I am doing a selection, and on highlight i adding a space. when user select the same span, i console the message.
all working fine. but when i select a existing node element (strong) with space, i am getting an error as The Range has partially selected a non-Text node.
how to solve this?
here is my code :
var currentTarget = null;
function selHTML() {
var nNd = document.createElement("span");
var w = getSelection().getRangeAt(0);
var text = window.getSelection().toString();
currentTarget = $(w.startContainer).parent();
//console.log(selection.anchorNode.baseURI);//nextElementSibling/anchorNode
if(!$(w.startContainer).parent().prop('class')) {
if($.trim(text).length < 5 ) {
console.log("Your selection is too short..!");
return;
}
try {
w.surroundContents(nNd);
currentTarget.find('span.highlight').contents().unwrap();
$(nNd).addClass('highlight');
} catch (ex) {
console.log("The Range has partially selected a non-Text node.")
}
} else {
console.log("already selected");
}
}
$("#addText").on('click', function(event) {
event.preventDefault();
$(selHTML());
});
$("button").click(function(){
$(selHTML());
});
$("#clearSpan").click(function(){
console.log($(currentTarget))
});
$("div.content").mouseup(function(event) {
var range = window.getSelection().getRangeAt(0);
if (!range.collapsed) {
var bounds = range.getBoundingClientRect();
var x = bounds.left + ((bounds.right - bounds.left - $(".savetooltipAll").outerWidth()) / 2);
var y = bounds.top - $(".savetooltipAll").outerHeight() + $(window).scrollTop();
$(".savetooltipAll").css("top", (y+(bounds.top*3)) + 'px');
$(".savetooltipAll").css("left",x + 'px');
$(".savetooltipAll").show();
} else {
$(".savetooltipAll").hide();
}
});
Demo
Highlight selected text on a page when spanning multiple non text nodes:
Highlight selected text on a page when spanning multiple non text nodes
i am using inputTextArea. Actually i want to limit it's max length. I am using function like
<script type="text/javascript">
function limitTextArea(element, limit) {
if (element.value.length > limit) {
element.value = element.value.substring(0, limit);
}
}
</script>
<textarea id="description" name="description"
onkeyup="limitTextArea(this, 1000);"
onkeydown="limitTextArea(this, 1000)">
</textarea>
But what is happening suppose i write a long text in the textarea. A scrollbar is shown in the textarea. But when i reach the maxlimit and then try to write a character then the textarea scrollbar move to top.
I want that once user reach it's max limit then the scrollbar as well as cursor stuck at that position.
Why it is behaving like textarea scrollbar move to top when i try to write something after max limit?
Thanks
Referred:How to impose maxlength on textArea in HTML using JavaScript
window.onload = function() {
var txts = document.getElementsByTagName('TEXTAREA')
for(var i = 0, l = txts.length; i < l; i++) {
if(/^[0-9]+$/.test(txts[i].getAttribute("maxlength"))) {
var func = function() {
var len = parseInt(this.getAttribute("maxlength"), 10);
if(this.value.length > len) {
alert('Maximum length exceeded: ' + len);
this.value = this.value.substr(0, len);
return false;
}
}
txts[i].onkeyup = func;
txts[i].onblur = func;
}
}
}
http://viralpatel.net/blogs/2008/12/set-maxlength-of-textarea-input-using-jquery-javascript.html
You can use this also to prevent the user from writing more than you want in a textarea.
Atleast this code prevents my textarea from scrolling to top
jQuery(document).ready(function($) {
$('textarea.max').keyup(function() {
var $textarea = $(this);
var max = 400;
if ($textarea.val().length > max) {
var top = $textarea.scrollTop();
$textarea.val($textarea.val().substr(0, max));
$textarea.scrollTop(top);
}
});
}); //end if ready(fn)
Here is the reference from which i got the idea to use it like this
How to prevent textarea from scrolling to the top when its value changed?
Better Solution:
jQuery(document).ready(function($) {
var max = 400;
$('textarea.max').keypress(function(event) {
if (event.which < 0x20) {
// e.which < 0x20, then it's not a printable character
// e.which === 0 - Not a character
return; // Do nothing
}
if (this.value.length == max) {
event.preventDefault();
} else if (this.value.length > max) {
// Maximum exceeded
this.value = this.value.substring(0, max);
}
}); //end of keypress(fn)
}); //end if ready(fn)
Thanks