Translating jQuery to javascript [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm new to SO and to JS. I want to translate this code to pure JS but I'm really struggling. May someone help me please?
$(document).ready(function(){
var displayFix = function(num) {
if (num.length > 9) {
total.text(num.substr(0,9));
}
};
var number = "";
var newNumber = "";
var operator = "";
var total = $(".display");
total.text("0");
$(".numbers span").not(".clear, .dot").click(function(){
number += $(this).text();
total.text(number);
displayFix(number);
});
$(".dot").click(function() {
if ( number.length == 0)
{ number = "0.";
} else {
number += $(this).text();
total.text(number);
displayFix(number);
};
});
$(".operators span").not(".igual").click(function(){
operator = $(this).text();
newNumber = number;
number = "";
total.text("0");
});
$(".clear").click(function(){
number = "";
total.text("0");
newNumber = "";
});
$(".igual").click(function(){
if (operator === "+"){
number = (parseFloat(newNumber,10) + parseFloat(number,10)).toString(10);
} else if (operator === "-"){
number = (parseFloat(newNumber,10) - parseFloat(number,10)).toString(10);
} else if (operator === "/"){
number = (parseFloat(newNumber,10) / parseFloat(number,10)).toString(10);
} else if (operator === "*"){
number = (parseFloat(newNumber,10) * parseFloat(number,10)).toString(10);
}
total.text(number);
displayFix(number);
number = "";
newNumber = "";
});
$(document).keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode === 49) {
$("#num1").click();
} else if (keycode === 50) {
$("#num2").click();
} else if (keycode === 51) {
$("#num3").click();
}
});
});
I suppose I can replace the following lines:
var total = $(".display") with var total = document.querySelector(".display")
total.text("0") with total.innerHTML="0"
$(".dot").click(function() { with document.querySelector(".dot").onclick = function() {
Also, the browser I'm using is a updated Chrome and I don't need it to support other browsers.

youmightnotneedjquery is your friend.
You'll see that you can define your own replacement for jQuery.ready():
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
Then you'll need to get used to do without jQuery wrapper, which means dealing with array indexes and possibly empty results. So for instance document.querySelector(".dot").onclick = function() { is not going to be enough, you want to do
var dots = document.querySelector(".dot");
for(var i=0; i<dots.length; i++ ){
dots[i].onclick = function() { ... }
}
Finally, you need to discard elements manually since you have no jQuery .not():
var operators = document.querySelector(".operators span");
for(var i=0; i<operators.length; i++ ){
var operator = operators[i];
if(operator.className.indexOf("igual") < 0){
//do stuff
}else{
//don't
}
}
Note: you may want to use document.getElementById() and document.getElementsByClassName when your selector is just an id or a class.
Hope this short guidance is enough for you to start.

The Javascript equivalent will almost look like this for your jquery code,
(function() {
var displayFix = function(num) {
if (num.length > 9) {
total.innerHTML = num.substr(0, 9);
}
};
var number = "";
var newNumber = "";
var operator = "";
var total = document.getElementsByClassName("display");
total.innerHTML = "0";
var sel1 = document.querySelector(".numbers span");
for (var i = sel1.length; i--;) {
if (sel1[i].className != 'clear' && sel1[i].className != 'dot') {
var arg = sel1[i].innerHTML;
sel1[i].onclick = function(arg) {
return function() {
number += arg;
total.innerHTML = number;
displayFix(number);
};
};
}
}
var sel2 = document.querySelector(".dot");
sel2.onclick = function() {
if (number.length == 0) {
number = "0.";
} else {
number += sel2.innerHTML;
total.innerHTML = number;
displayFix(number);
};
};
var sel3 = document.querySelector(".operators span");
for (var i = sel3.length; i--;) {
if (sel3[i].className != 'igual') {
var arg = sel3[i].innerHTML;
sel3[i].onclick = function(arg) {
return function() {
operator = arg;
newNumber = number;
number = "";
total.innerHTML = "0";
};
};
}
}
document.querySelector(".clear").onclick = function() {
number = "";
total.innerHTML = "0";
newNumber = "";
};
document.querySelector(".igual").onclick = function() {
if (operator === "+") {
number = (parseFloat(newNumber, 10) + parseFloat(number, 10)).toString(10);
} else if (operator === "-") {
number = (parseFloat(newNumber, 10) - parseFloat(number, 10)).toString(10);
} else if (operator === "/") {
number = (parseFloat(newNumber, 10) / parseFloat(number, 10)).toString(10);
} else if (operator === "*") {
number = (parseFloat(newNumber, 10) * parseFloat(number, 10)).toString(10);
}
total.innerHTML = number;
displayFix(number);
number = "";
newNumber = "";
};
document.querySelector(".igual").onkeypress = function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
var elm = "";
if (keycode === 49) {
elm = document.getElementById("num1");
elm.onclick.apply(elm);
} else if (keycode === 50) {
elm = document.getElementById("num2");
elm.onclick.apply(elm);
} else if (keycode === 51) {
elm = document.getElementById("num3");
elm.onclick.apply(elm);
}
};
})();
Disclaimer: The code is just converted to the JavaScript equivalent, not tested with any values.

Related

not going to the if statement in javascript

everything is working properly only the control is not moving to the if statement
let fnum, snum, operator;
const op = ["+", "-", "*", "/", "%"];
let fnumUi = document.getElementById("fnumUI");
let snumUi = document.getElementById("snumUI");
let opUi = document.getElementById("opUI");
var input = document.getElementById("user_input");
let scoreUi = document.getElementById("score");
input.addEventListener("keypress", myFunction(event));
function myFunction(event) {
let answer = 8;
if (event.keyCode === 13) {
let user_ans = Number(input.value);
input.value = '';
fnum = Number(Math.floor(Math.random() * 20));
snum = Number(Math.floor(Math.random() * 20));
operator = op[Math.floor(Math.random() * op.length)];
fnumUi.innerHTML = fnum;
snumUi.innerHTML = snum;
opUi.innerHTML = operator;
if (operator === "+") {
answer = fnum + snum;
} else if (operator === "-") {
answer = fnum - snum;
} else if (operator === "*") {
answer = fnum * snum;
} else if (operator === "/") {
answer = fnum / snum;
} else {
answer = fnum % snum;
}
if (answer === user_ans) {
scoreUi.innerHTML = Number(scoreUi.innerHTML) + 3;
} else {
scoreUi.innerHTML = scoreUi.innerHTML - 1;
}
}
}
answer is updating but for this part of code
if (answer === user_ans) {
scoreUi.innerHTML = Number(scoreUi.innerHTML) + 3;
} else {
scoreUi.innerHTML = scoreUi.innerHTML - 1;
}
even when i write the correct answer it moves to else statement. not getting into if statement
so instead of adding 3 in score it is deducting 1 from the score.
You need to pass the function itself rather than the results of its call.
input.addEventListener("keypress",myFunction);

Encode letter to number

I feel like I am failing everything this semester. but I was wondering if you all could help me with a JS project. We have been tasked with essentially converting numbers to letters and vica versa using textareas in HTML. I was able to do the numbers to letters function, but am having difficulties going the other way. what I have for all is:
var $ = function(id) {
return document.getElementById(id);
};
window.onload = function() {
$("btnDecode").onclick = fnDecode;
$("btnEncode").onclick = fnEncode;
$("btnClear").onclick = fnClear;
};
function fnDecode() {
var msg = $("textin").value;
if (msg === "") {
$("textin_span").innerHTML = "* Please enter a message to decode *";
$("textin").focus;
return;
} else {
$("textin_span").innerHTML = "";
}
var nums = msg.split(",");
var outstr = "";
for(var i=0; i < nums.length; i++) {
var n2 = parseInt(nums[i]);
if (isNaN(n2)) {
outstr += "?";
} else if (isNallN(nums[i])) {
} else if (n2 === 0) {
outstr += " ";
} else if (n2 < 1 || n2 > 26) {
outstr += "?";
} else {
outstr += String.fromCharCode(n2+64);
}
$("textout").value = outstr;
}
}
function isNallN(s) {
//parse string to check all characters are digits
}
function fnEncode() {
var msg = $("textin").value.toUpperCase();
$("textin").value = msg;
if (msg === "") {
$("textin_span").innerHTML = "* Please enter numberse to decode *";
$("textin").focus;
return;
} else {
$("textin_span").innerHTML = "";
}
var c;
var outstr = "";
for (var i=0; i<msg.length; i++);
c = msg.charCodeAt(i);
if (typeof c === "number") {
outstr += "99";
}else if (c === " ") {
outstr += 0;
/*} else if (c[i] >= "A" && c[i] <= "Z") {
outstr += "99";*/
} else {
outstr += String.charCodeAt(c - 64);
}
$("textout").value = outstr;
//var x = msg.charAT(i);
}
obviously isNallN is not complete, but he promised us if we could figure out fnEncode we should be able to do isNallN with no issues (which I am hoping is true lol) What am doing wrong though in fnEncode? Every time I run it, it gives me "99" even when I put letters in.

four repeating letters check javascript, spam detection

Is there a a "smarter" way to do this? This works but I imagine has something to do with for loops, what if I was checking for 20 repeating characters?
What happens if javascript is disabled?
Is there an easier way to check for "sensical" posts instead of say aldjfalkfja;lfjaklfjlkfj how would I filter that out without storing a library of words and comparing the string to those?
function counter(){
this.value = 0;
}
var count = new counter();
function updatecount(fnc){
fnc.value = count.value + 1;
}
function charbank1(){
this.value = "";
}
var cb1 = new charbank1();
function insertchar1(fnc){
fnc.value = cb1.value + String.fromCharCode(keynum);
}
function charbank2(){
this.value = "";
}
var cb2 = new charbank2();
function insertchar2(fnc){
fnc.value = cb2.value + String.fromCharCode(keynum);
}
function charbank3(){
this.value = "";
}
var cb3 = new charbank3();
function insertchar3(fnc){
fnc.value = cb3.value + String.fromCharCode(keynum);
}
function charbank4(){
this.value = "";
}
var cb4 = new charbank4();
function insertchar1(fnc){
fnc.value = cb4.value + String.fromCharCode(keynum);
}
function repeatingcharcheck(){
if(count.value < 4){
if(count.value == 1){
insertchar1(cb1);
}
if(count.value == 2){
insertchar2(cb2);
}
if(count.value == 3){
insertchar3(cb3);
}
if(count.value == 4){
insertchar4(cb4);
}
}else{
if(cb1.value == cb2.value == cb3.value == cb4.value){
alert('four letters in a row is not allowed');
window.location.replace('somewhere.com');
}
}
}

Javascript Check variable.Then gain ++ per second

I have a problem i want to check a variable.If its 0 then gain ++ after 1.5s.If its 10 then gain ++ after .4s.Its complicated.It doesnt really work.My code so far:
if(road == 1){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1400);}
else if(road == 2){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1300);}
else if(road == 3){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1200);}
else if(road == 4){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1100);}
else if(road == 5){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1000);}
else if(road == 6){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},900);}
else if(road == 7){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},800);}
else if(road == 8){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},600);}
else if(road == 9){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},400);}
else if(road == 10){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},200);}
else{setInterval(function(){stamina++;document.getElementById("stamina").innerHTML = stamina;},1500);}
And the code to build a road is this:
function build_road() {
if ((wood + tavern) >= 29 && stone > 4 && road < 10) {
road++;
document.getElementById("road_count").innerHTML = road;
wood = (wood + tavern) - 20;
stone = stone - 5;
document.getElementById("wood").innerHTML = wood;
document.getElementById("stone").innerHTML = stone;
exp = exp + 20;
var x = document.getElementById("PROGRESS");
x.setAttribute("value", exp);
x.setAttribute("max", max);
if (exp == 100) {
exp = 0;
level++;
document.getElementById("level").innerHTML = level;
}
alert("Congratulations,You've create a Road,Now you gain stamina slightly faster.");
}
else {
alert("You need: 30Wood,5Stone .Maximum 10 Roads.")
}
}
Make reusable functions (it's often a good practice, when you a difficulties with a piece of code, to break it into small functions):
var staminaIncreaseTimer = null;
function configureStaminaIncrease(delay) {
if (staminaIncreaseTimer !== null)
clearInterval(staminaIncreaseTimer);
staminaIncreaseTimer = setInterval(function () {
increaseStamina();
}, delay);
}
function increaseStamina() {
stamina += 1;
document.getElementById("stamina").innerHTML = stamina;
}
Solution with an array (suggested by Jay Harris)
var roadIndex = road-1;
var ROAD_DELAYS = [1400, 1300, 1200, /*...*/];
var DEFAULT_DELAY = 1500;
if (roadIndex < ROAD_DELAYS.length) {
configureStaminaIncrease(ROAD_DELAYS[roadIndex]);
} else {
configureStaminaIncrease(DEFAULT_DELAY);
}
Solution with a switch instead of you if-elseif mess:
switch (road) {
case 1:
configureStaminaIncrease(1400);
break;
case 2:
configureStaminaIncrease(1300);
break;
case 3:
configureStaminaIncrease(1200);
break;
//and so on...
default:
configureStaminaIncrease(1500);
}

mask work for id but not for class

hi i have a problem with my javascript code it works for input by id but i wat to use it on class element. I do not know what is i am doing wrong any idea? I paste my code
i want to mask time on my input
function maska(inputName, mask, evt) {
var text = document.getElementsByClassName(inputName);
try {
var value = $(text).val(); //text.value;
// Jeśli ktoś naciśnie dela lub backspace to czyszcze inputa
try {
var e = (evt.which) ? evt.which : event.keyCode;
if (e == 46 || e == 8) {
$(text).val() = ""; //text.value = "";
return;
}
} catch (e1) { }
var literalPattern = /[0\*]/;
var numberPattern = /[0-9]/;
var newValue = "";
for (var vId = 0, mId = 0; mId < mask.length; ) {
if (mId >= value.length)
break;
// Wpada jakaś inna wartość niż liczba przechowuje tylko ta dobra wartosc
if (mask[mId] == '0' && value[vId].match(numberPattern) == null) {
break;
}
// Wpadł literał
while (mask[mId].match(literalPattern) == null) {
if (value[vId] == mask[mId])
break;
newValue += mask[mId++];
}
var godzina = value.substr(0, 2);
var minuty = value.substr(3,4);
if (minuty > '59' || godzina > '23') {
break;
}
else
newValue += value[vId++];
mId++;
}
text.val() = newValue;
//text.value = newValue;
} catch (e) { }
}
getElementById returns a single DOMElement while getElementsByClass returns an array of elements. To allow for both, you could have one function that accepts a DOMElement and two functions that find the elements, one for id and one for class:
function maska(elem, mask, evt) {
try {
var value = $(elem).val();
// blah blah, rest of the function
}
function maskById(id, mask, evt) {
var element = document.getElementById(id);
maska(element, mask, evt);
}
function maskByClass(class, mask, evt) {
var element_list = document.getElementsByClass(class);
for(var i = 0; var i < element_list.length; i++) {
maska(element_list[i], mask, evt);
}
}
But you would be better off using the jquery selector combined with .each , which always returns results as a set/array, regardless of selector type.
document.getElementById returns a single element, which your code is written to handle.
document.getElementsByClassName returns multiple elements. You need to loop over them and process them each individually.
I don't get why you use getElementsByClassName and then use jQuery features?
try $('input.' + inputName)
getElementById returns a single element, while getElementsByClassName returns a collection of elements. You need to iterate over this collection
function maska(inputName, mask, evt) {
var text = document.getElementsByClassName(inputName);
try {
for (var i = 0; i < text.length; i++) {
var value = text[i].value;
// Jeśli ktoś naciśnie dela lub backspace to czyszcze inputa
try {
var e = (evt.which) ? evt.which : event.keyCode;
if (e == 46 || e == 8) {
text[i].value = "";
continue;
}
} catch (e1) { }
var literalPattern = /[0\*]/;
var numberPattern = /[0-9]/;
var newValue = "";
for (var vId = 0, mId = 0; mId < mask.length; ) {
if (mId >= value.length)
break;
// Wpada jakaś inna wartość niż liczba przechowuje tylko ta dobra wartosc
if (mask[mId] == '0' && value[vId].match(numberPattern) == null) {
break;
}
// Wpadł literał
while (mask[mId].match(literalPattern) == null) {
if (value[vId] == mask[mId])
break;
newValue += mask[mId++];
}
var godzina = value.substr(0, 2);
var minuty = value.substr(3,4);
if (minuty > '59' || godzina > '23') {
break;
}
else
newValue += value[vId++];
mId++;
}
text[i].value = newValue;
}
} catch (e) { }
}

Categories

Resources