How does Stack Overflow do the character counter saying xyz characters left?
Probably something like (with jQuery):
$('#txtbox').keypress(function() {
var max = 500;
var textLen = $(this).val().length;
var textLeft = max - textLen;
$('#charCount').text(
textLeft + ' character' + (textLeft == 1 ? '' : 's') + ' left'
);
});
(I know it's lazy to not actually look and see how they do it, but here's a working example: http://jsfiddle.net/FishBasketGordo/hqex8/)
HTML:
<textarea id="text" onkeyup="charCount(this);"></textarea>
<span id="chars"></span>
JS:
var maxChars = 500;
function charCount(el) {
document.getElementById('chars').innerText = maxChars - this.value.length;
}
not tested, but that's the basics.
This can be done several ways but here is a link to some simple source code. The only for sure way to know how SO does it is to look into there compressed javascript.
http://javascript.internet.com/forms/character-counter.html
Have a look at this page on one of my sites http://www.bestvaluesolicitors.com/contact-us
Peek at the JS - you are looking for this function:
function ml(id,max,repeat){if($F(id).length>max){$(id).value=$F(id).substring(0,max);}$(id).next('div').update($F(id).length+' / '+max+' characters');if(repeat==true){setTimeout('ml("'+id+'",'+max+','+repeat+')',500);}}
Esentially it is a combination of a timer and counting the length of text in the textarea
Probably something like this:
var max = 1000;
document.getElementById('freddy').onkeypress =
document.getElementById('freddy').onkeyup =
document.getElementById('freddy').onkeydown = function(){
var count = this.value.length;
if(max < count){
this.value = this.value.substring(0,999);
return false;
}
setTimeout(function(){
document.getElementById('susan').innerHTML =
(max-count)+' characters left!';
},1);
};
http://jsfiddle.net/Paulpro/S4Dtu/
Here is the definition of StackExchange's charCounter() method. It's a little obfuscated, but you can find the logic if you dig through it:
charCounter: function(c) {
return this.each(function() {
var d = $(this).parents("form").find("span.text-counter");
var e = this;
var f = function() {
var j = c.min;
var l = c.max;
var k = c.setIsValid || function() {};
var h = e.value ? e.value.length : 0;
var i = h > l * .8 ? "supernova" : h > l * .6 ? "hot" : h > l * .4 ? "warm" : "cool";
var g = "";
if (h == 0) {
g = "enter at least " + j + " characters";
k(false);
} else {
if (h < j) {
g = j - h + " more to go..";
k(false);
} else {
g = l - h + " character" + (l - h != 1 ? "s" : "") + " left";
k(h <= l);
}
}
d.text(g);
if (!d.hasClass(i)) {
d.removeClass("supernova hot warm cool").addClass(i);
}
};
$(this).bind("blur focus keyup", a.DelayedReaction(f, 100, {
sliding: true
}).trigger);
});
}
And the comment text areas, for example, are set up like so (again, obfuscated):
var x = z.find("textarea");
x.charCounter({
min: 15,
max: 600,
setIsValid: A
});
Related
I love this JS Parallax technique used in this website
https://www.beamland.com/
Based on scrolling a set div, change in css VH, showing what is under.
I am trying to reproduce something similar, but I am failing to get the formula of calculating the height of the visible screen vs the scroll, vs the whole height of the document.
So I digged under the hood of that website, but I am not understanding what kind of calculation is being done to achieve the effect.
BEAM.initParallax = function() {
function a() {
var a = q - 1,
b = a / j,
c = Math.ceil(b),
d = 100 - a % j / j * 100 + "vh",
e = 100 * b + 4e3 / j + "vh";
r = !1, "Mobile Safari" !== h.browser.name && "Android" !== h.os.name || (e = a + 30 + "px"), c < 1 && (c = 1), a % j === 0 && a > 0 && c++;
for (var f = 0; f < m.length; f++) f + 1 > c ? m[f].style.height = "100vh" : f - 1 < c && (m[f].style.height = "0vh");
m[c - 1] && (m[c - 1].style.height = d), o.removeClass("is-active"), $(o[c - 1]).addClass("is-active"), b < s ? (l.removeAttr("style").addClass("stuck"), n.removeClass("faded")) : l[0].hasAttribute("style") || (n.addClass("faded"), l.removeClass("stuck").css("top", e))
}
function b() {
if (s = 3.887, k <= 1024) {
s = 3.915;
var a = Math.abs(j - document.getElementsByClassName("Parallax-spacer")[0].style.height);
$(".Parallax-spacer").css("height", j + "px"), a > 20 && Math.ceil((q - 1) / j) >= 4 && (p < q && (a *= -1), window.scrollTo(0, q - 4 * a))
}
}
function c() {
return "Android" === h.os.name ? i.outerHeight() : i.innerHeight()
}
function d() {
return "Android" === h.os.name ? i.outerWidth() : i.outerWidth()
}
function e() {
p = q, q = window.scrollY, f()
}
function f() {
r || window.requestAnimationFrame(a), r = !0
}
if ($(".Parallax-Hero").length) {
var g = new UAParser,
h = g.getResult(),
i = $(window),
j = c(h),
k = d(h),
l = $("div.Nav-Main"),
m = $(".Parallax-panel"),
n = $(".Parallax-wayfinder"),
o = n.find(".Parallax-pagination--dot"),
p = 0,
q = 0,
r = !1,
s = 0;
b(), $(".Parallax-pagination--dot").on("mouseup touchend", function(a) {
a.preventDefault();
var b = $(".Parallax-pagination--dot").index(this),
c = b * j + 1;
$("html, body").animate({
scrollTop: c + "px"
}, 500)
}), i.on("scroll", function() {
e()
}), i.on("resize", function() {
j = c(h), k = d(h), b(), e()
}), window.requestAnimationFrame(a)
}
I even looked at various other parallax and code effect on codepen, but I don't find something similar to this effect, to understand the calculation.
Can someone help me to unveil the logic? Thank you
This is a minified code. For development purposes, you better rename the variables so you could read easily.
m = $(".Parallax-panel"),
becomes:
parallaxPanel = $(".Parallax-panel"),
then
m.length
is
parallaxPanel.length
q = window.scrollY
becomes
windowScrollY = window.scrollY
then
a = windowScrollY - 1;
j = c(h),
becomes
windowHeight = c(h),
Try this ad see if you could understend better.
Update:
The reason I suggested this naming convention is for you to understand these calculations better.
b = a / j;
This is not clear, but:
b = (windowScrollY - 1) / windowHeight;
is more obvious. window.ScrollY is the number of pixels the document is currently scrolled vertically from the origin. window.outerHeight is window's height.
c = Math.ceil(b);
b is float so now c is an integer.
d = 100 - a % j / j * 100 + "vh";
d = 100 - (windowScrollY - 1) % windowHeight / windowHeight * 100 + "vh";
This gives percentage scrolled.
I won't be able to decode it all for you. You should have math and programming knowledge to do it.
I am working on my bachelors work, and I am building something like interpreter. I want to convert the Javascript code into Python. I came to a point that I want to convert For Loop into Python which looks like this:
for(var x = 0; x < some_length; x++) {
}
in python it would look like this:
for x in range(0, some_length):
the problem is I want to cover all the cases that can happen, like for example going backwards like this:
for(var x = some_length - 1; x >= 0; x--) {
}
can somebody help me to write a function that will transpile this into python?
IMPORTANT EDIT!!!
as input to the function that will transpile the for loop into python are:
function pythonize(firstAction, condition, action)
where
firstAction = "x = 0",
condition = "x < some_length"
action = "x++"
It will be like, you can check range function for more of its detailed usage:
for x in range(some_length - 1, -1, -1):
Notice I change the step from x++ to decrement, otherwise the for loop won't terminate.
range accepts start, end, step, so you can do
for x in range(some_length-1, -1, -1)
Another option is
for x in reversed(range(some_length))
note: I assume you mean x-- in your second example
I've created this long function to transpile javascript for loop into python for loop:
function pyt(c) {
var cc = c.split('(')[1];
cc = cc.substr(0,cc.length-1);
pp = cc.split(';');
var r1 = /[A-Za-z\$\_]{1}[A-Za-z0-9\_]* ?= ?(.*)/.exec(pp[0])[1];
var r2 = '';
if(pp[1].indexOf('<') > -1) {
r2 = /[A-Za-z\$\_]{1}[A-Za-z0-9\_]* ?<=? ?(.*)/.exec(pp[1])[1]
} else if(pp[1].indexOf('>') > -1) {
r2 = /[A-Za-z\$\_]{1}[A-Za-z0-9\_]* ?>=? ?(.*)/.exec(pp[1])[1]
}
var delta = 0;
if(pp[1].indexOf('>=')) {
delta = -1;
}
if(pp[1].indexOf('<=')) {
delta = 1;
}
var e2 = 0;
if(!isNaN(r2)) {
e2 = Number(r2) + delta;
} else {
if(delta !== 0) {
e2 = r2 + (delta > 0 ? '+' : '-') + delta;
} else {
e2 = r2;
}
}
var r3 = '';
if(/[A-Za-z\$\_]{1}[A-Za-z0-9\_]*\+\+/.test(pp[2])) {
r3 = '1';
} else if(/[A-Za-z\$\_]{1}[A-Za-z0-9\_]*\-\-/.test(pp[2])) {
r3 = '-1';
} else {
if(pp[2].indexOf('+=') > -1) {
r3 = /[A-Za-z\$\_]{1}[A-Za-z0-9\_]* ?\+= ?(.*)/.exec(pp[2])[1];
} else if(pp[2].indexOf('-=') > -1) {
r3 = /[A-Za-z\$\_]{1}[A-Za-z0-9\_]* ?\-= ?(.*)/.exec(pp[2])[1];
} else {
if(/([A-Za-z\$\_]{1}[A-Za-z0-9\_]*) ?= ?\1 ?\+ ?(.*)/.test(pp[2])) {
r3 = /([A-Za-z\$\_]{1}[A-Za-z0-9\_]*) ?= ?\1 ?\+ ?(.*)/.exec(pp[2])[2];
} else {
r3 = /([A-Za-z\$\_]{1}[A-Za-z0-9\_]*) ?= ?\1 ?\- ?(.*)/.exec(pp[2])[2];
}
}
}
p = 'for i in range(' + r1 + ', ' + e2 + ', ' + r3 + ')';
return p;
}
var c = "for(i = 30 + y;i>=10 - 1; i = i + 0.1)";
console.log(pyt(c));
https://jsfiddle.net/x7uhxbua/12/
It's basically using regex to do the magic. It covers most of the cases, but not all.
using Daniel Crisp's angular range slider http://danielcrisp.github.io/angular-rangeslider/. . would like use floating values from min: 0 - max: 1
step of 0.1 (0, 0.1, 0.2, 0.3,...)
What if you do a math cur / 100 while min should be 0 and max 100?
got it. secret was in the filter:
app.filter('hourMinFilter', function () {
return function (value) {
if (value === 120) return 'All'
var h = parseInt(value / 100);// changed this
var m = parseInt(value % 100);// changed this
m = '0.' + m; // added this
var hStr = (h > 0) ? h + 'dollars' : ''; // changed this
var mStr = (m > 0) ? m + 'cents' : ''; // changed this
var glue = (hStr && mStr) ? ' ' : '';
return hStr + glue + mStr;
};
});
worked turned into dollars and cents
I need to create a function or use if is possible an already made library to auto increment an index. For example if it starts with 'A' it has to be incremented to 'Z' and after 'Z' it has to start from 'A1' and as soon as . . .'B1','C1', ... 'Z1', 'A2','B2',... . Does exist something like this already made ?
My idea is this, but start from 'A' and don't add number . . .
function nextChar(cont,letter) {
if (cont === 0){return letter;}
else {
letter=letter.charCodeAt(0) + 1;
return String.fromCharCode(letter);
}
}
One of many options:
function nextIndex(idx) {
var m = idx.match(/^([A-Z])(\d*)$/)
if(!m)
return 'A';
if(m[1] == 'Z')
return 'A' + (Number(m[2] || 0) + 1);
return String.fromCharCode(m[1].charCodeAt(0) + 1) + m[2];
}
var a = "";
for(i = 0; i < 100; i++) {
a = nextIndex(a)
document.write(a + ", ")
}
This one's less efficient than georg's but maybe easier to understand at first glance:
for (var count = 0, countlen = 5; count < countlen; count++) {
for (var i = 65, l = i + 26; i < l; i++) {
console.log(String.fromCharCode(i) + (count !== 0 ? count : ''));
}
}
DEMO
Allow me to propose a solution more object-oriented:
function Index(start_with) {
this.reset = function(reset_to) {
reset_to = reset_to || 'A';
this.i = reset_to.length > 1 ? reset_to[1] : 0; // needs more input checking
this.c = reset_to[0].toUpperCase(); // needs more input checking
return this;
};
this.inc = function(steps) {
steps = steps || 1;
while(steps--) {
if (this.c === 'Z') {
this.i++;
this.c = 'A';
} else {
this.c = String.fromCharCode(this.c.charCodeAt(0) + 1);
}
}
return this;
};
this.toString = function() {
if (this.i === 0) return this.c;
return this.c + '' + this.i;
};
this.reset(start_with);
}
var a = new Index(); // A
console.log('a = ' + a.inc(24).inc().inc()); // Y, Z, A1
var b = new Index('B8'); // B8
console.log('a = ' + a.reset('Y').inc()); // Y, Z
console.log('b = ' + b); // B8
Another way to think about this is that your "A1" index is just the custom rendering of an integer: 0='A',1='B',26='A1',etc.
So you can also overload the Number object to render your index. The big bonus is that all the math operations still work since your are always dealing with numbers:
Number.prototype.asIndex = function() {
var n = this;
var i = Math.floor(n / 26);
var c = String.fromCharCode('A'.charCodeAt(0) + n % 26);
return '' + c + (i ? i : '');
}
Number.parseIndex = function(index) {
var m;
if (!index) return 0;
m = index.toUpperCase().match(/^([A-Z])(\d*)$/);
if (!m || !m[1]) return 0;
return Number((m[1].charCodeAt(0) - 'A'.charCodeAt(0)) + 26 * (m[2] ? m[2] : 0));
};
var c = 52;
var ic = c.asIndex();
var nc = Number.parseIndex(ic);
console.log(c+' = '+ic+' = '+nc); // 52 = A2 = 52
If you go this way I would try to check if the new methods don't already exist first...
I wanted to write a method to escape special chars like 'ä' to their responding Unicode (e.g. \u00e4).
For some reason JS finds it amusing to not even save the 'ä' internally but use 'üÜ' or some other garble, so when I convert it spits out '\u00c3\u00b6\u00c3\u002013' because it converts these chars instead of 'ä'.
I have tried setting the HTML file's encoding to utf-8 and tried loading the scripts with charset="UTF-8" to no avail. The code doesn't really do anything special but here it is:
String.prototype.replaceWithUtf8 = function() {
var str_newString = '';
var str_procString = this;
for (var i = 0; i < str_procString.length; i++) {
if (str_procString.charCodeAt(i) > 126) {
var hex_uniCode = '\\u00' + str_procString.charCodeAt(i).toString(16);
console.log(hex_uniCode + " (" + str_procString.charAt(i) + ")");
str_newString += hex_uniCode;
} else {
str_newString += str_procString.charAt(i);
}
}
return str_newString;
}
var str_item = "Lärm, Lichter, Lücken, Löcher."
console.log(str_item); // Lärm, Lichter, Lücken, Löcher.
console.log(str_item.replaceWithUtf8()); //L\u00c3\u00a4rm, Lichter, L\u00c3\u00bccken, L\u00c3\u00b6cher.
I have no idea how or why but I just restarted the server again and now it's displaying correctly. To follow up; here's the code for everyone who's interested:
String.prototype.replaceWithUtf8 = function() {
var str_newString = '';
var str_procString = this;
var arr_replace = new Array('/', '"');
var arr_replaceWith = new Array('\\/', '\\"');
for (var i = 0; i < str_procString.length; i++) {
var int_charCode = str_procString.charCodeAt(i);
var cha_charAt = str_procString.charAt(i);
var int_chrIndex = arr_replace.indexOf(cha_charAt);
if (int_chrIndex > -1) {
console.log(arr_replaceWith[int_chrIndex]);
str_newString += arr_replaceWith[int_chrIndex];
} else {
if (int_charCode > 126 && int_charCode < 65536) {
var hex_uniCode = '\\u' + ("000" + int_charCode.toString(16)).substr(-4);
console.log(hex_uniCode + " (" + cha_charAt + ")");
str_newString += hex_uniCode;
} else {
str_newString += cha_charAt;
}
}
}
return str_newString;
}
Use '\\u' + ('000' + str_procString.charCodeAt(i).toString(16) ).stubstr(-4); instead to get the right escape sequences - yours do always start with 00. Also, instead of a for-loop processing your string, .replace() might be faster.
On your question:
console.log("Lärm, Lichter, Lücken, Löcher."); // Lärm, Lichter, Lücken, Löcher.
does not sound as you really sent the file with the right encoding. Might be a server problem, too, if it is correctly saved already.
String.prototype.replaceWithUtf8 = function() {
function r(r) {
for (var t, n, e = "", i = 0; !isNaN(t = r.charCodeAt(i++)); ) n = t.toString(16),
e += 256 > t ? "\\x" + (t > 15 ? "" :"0") + n :"\\u" + ("0000" + n).slice(-4);
return e;
}
var a, c, o, u, s, e = "", i = this, t = [ "/", '"' ], n = [ "\\/", '\\"' ];
for (a = 0; a < i.length; a++) c = i.charCodeAt(a), o = i.charAt(a), u = t.indexOf(o),
u > -1 ? e += n[u] :c > 126 && 65536 > c ? (s = r(o), e += s) :e += o;
return e;
};
prompt("Your escaped string:","Lärm, Lichter, Lücken, Löcher.".replaceWithUtf8());
alert("L\xe4rm, Lichter, L\xfccken, L\xf6cher.");
Unicode encoding only makes every character 6 digits. But for characters above 127 to 256, we can actually make these hexdecimal with less bytes (4 digits per character).