Adding 1 to a css style property in Javascript - javascript

I am trying to first get the value of the order property of an element, and then adding 1 to it when I click a button. Thing is, instead of getting 1 and adding 1 and getting 2, I get 11. Shouldn't the "+=" operator add the values? What am I doing wrong?
carouselPrev.addEventListener("click", function(){
const firstPost = document.querySelector(".blog-post");
let firstPostOrder = firstPost.style.getPropertyValue('order');
firstPost.style.order = firstPostOrder += 1;
});

Css properties are strings, and '1' + 1 = 11.
Add "+" before firstPostOrder to convert it to a number.
firstPost.style.order = +firstPostOrder += 1;

the values are strings so they are be concatenated, try parsing to an integer before using parseInt()

Try this
carouselPrev.addEventListener("click", function(){
const firstPost = document.querySelector(".blog-post");
let firstPostOrder = firstPost.style.getPropertyValue('order');
firstPost.style.order = parseInt(firstPostOrder,10) +1;
});

No, the "+=" operator is an assignment operator you'd use in lieu of "=".
let x = 42;
x += 1;
is equivalent to
let x = 42;
x = x + 1;
You want to use just the "+" to add the values, not the "+=".

Related

Javascript display the last 3 numbers after the dot fixed(3) not working

I have a number which looks number this:
800.60000305176541
This number changes all the time.
So I'm doing this:
var mynumber = 800.60000305176541
var changenumber = mynumber.toFixed(3);
This is displaying 800.600 ... I need it to display the last 3 like:
800.541
How can I do this?
You can convert to string and do your manipulations.
Please note we are loosing the right most digit due to limits of javascript.
var num = 800.60000305176541;
var str = "" + num
var arr = str.split(".");
var result = arr[0]
if (arr[1]) {
result += "." + arr[1].slice(-3)
}
console.log(num)
console.log(result)
You could also try to solve it mathematically.
800.60000305176541
800.60000305176000 -
------------------
800.00000000000541
.00000000000541
10^10. X
------------------
0,541 + 800 = 800.541

Easy- Function arguments

I'm currently struggling with getting the below calcRatio function calculate properly. This is probably basic maths!
The below function works as expected:
function calcRatio(){
var r = frontRing.value/backCog.value;
return r;
}
e.g. frontRing = 52, backCog = 11 r=4.7272....
The below gives me the wrong result:
function calcRatio(){
var r = frontRing.value/(backCog.value + 5);
return r;
}
e.g. frontRing = 52, backCog = 11 r=0.4521.
I ultimately want the 5 to be swapped with an argument.
I am also unable to set the frontRing and backCog variable as .value's without doing it within the function. Could this be causing the issue?
Codepen link
When you expect the extracted value to be a string and have additional computations, it is preferred you use either
parseInt( value , 10) - for integers
parseFloat( value ) - for decimals
In the use case var r = frontRing.value/(backCog.value + 5);
backCog.value is a string since it it a value of input element. When you use + to add a number, it performs a concatenation instead of addition.
var backCogValue = backCog.value; // "11";
"11" + 5 --> 115 and not 16 as you expected.
So the right way to write this piece of code is to use either of the above methods before you want to add a number.
var frontRingValue = parseFloat(frontRing.value);
var backCogValue = parseFloat(backCog.value);
var r = (frontRingValue/ (backCogValue + 5)).toFixed(4);
toFixed is use to format into the number of decimal points that you are expecting.
If 5 is the argument that is passed to the function, then your code will look like
function calcRatio(param) {
var frontRingValue = parseFloat(frontRing.value);
var backCogValue = parseFloat(backCog.value);
var paramValue = parseFloat(paramValue);
var r = (frontRingValue/ (backCogValue + paramValue)).toFixed(4);
}

Dynamically wrap index with array using while loop

My code speaks for me, I want to wrap array index with another array dynamically (with a loop).
The following code does not work. Please, help me to convert this "x" string to JavaScript code or to find the right way to get the result.
var x = parentTasks[j];
while(x){
x = parentTasks + '[' + numbers + '[' + x + ']]';
}
Later "x" will become undefined, so then loop should stop.
What I expect:
Example when loop is iterated for 1st time:
parentTasks[numbers[parentTasks[j]]]
Example when loop is iterated for 2nd time:
parentTasks[numbers[parentTasks[numbers[parentTasks[j]]]]]
I did it by my self. Here is a solution:
var x = parentTasks[j];
var z = 0
while ( z++ < 2 ) {
x = 'parentTasks[numbers[' + x + ']]';
console.log(eval(x));
}

Javascript: cannot override concatenation

Using the following code I want to move a line with id='seekline' by var1 (less than .1 in most cases), but I run into trouble adding var1 and j.
The plus sign concatenates instead of adding. I have tried using Number(), parseInt(), parseFloat(), and forcing addition by multiplying by 1 or adding by 0. For some reason I cannot stop the concatenation. When I use parseInt() or parseFloat() (e.g. parseInt(j,10)) the code stops working.
The string split is to remove the px from element.style.left.
function move(var1) {
element = document.getElementById('seekline');
console.log(var1, element.style.left);
var str=(element.style.left);
var n=str.split("p");
var j = n[0];
Number(j);
Number(var1);
var k = var1 + j;
var f = k.concat("px");
console.log(j, k, f);
element.style.left = f;
}
You need to assign the result of the call to Number(), as it returns the numeric value of the string passed instead of modifying the variable itself.
Note that +foo is the same as doing Number(foo).
function move(var1) {
var style = document.getElementById('seekline').style;
// removes last two 'px' characters
var oldValue = +style.left.slice(0, -2);
// converts to number type, then adds 2 to it
var1 = +var1;
var1 += 2;
// check to see if number is NaN or +/-Infinity
if (isFinite(var1)) {
// only now string concatenates the term 'px' to it
element.style.left = oldValue + var1 + 'px';
}
}
function move(var1) {
var element = document.getElementById('seekline'),
left = parseInt(element.style.left.replace('px',''),10);
element.style.left = ((left++) + var1) + 'px';
}
The secret for you to work with numbers obtained from JavaScript, is to remove the string 'px' and convert them to numbers:
parseInt(element.style.left.replace('px', ''))

Javascript: why does this produce and ugly string??? I would like currency

var total = 0;
$(".amount").each(function () {
var value = $(this).val();
value = (value.length < 1) ? 0 : value;
var tmp = parseFloat(value).toFixed(2);
total += tmp;
});
$(".total").text(total);
I am trying to loop through some text boxes and sum up their values. This produces a nasty string. What am I missing?? if I put 8 in the first textbox total text ends up as " 08.000.000.000.00". What am I doing wrong? I would like to format as currency but if not, at least just a two decimal number. Any pointers?
.toFixed converts the object from a Number to a String.
Leave the full values in place and only convert using .toFixed at the very end
$(".total").text(total.toFixed(2));
Alternatively, convert the string back to a number.
total = total + + tmp;
Just FYI, there is an excellent mathematical aggregation plugin for jQuery: jQuery Calculation
Using that plugin may also indirectly solve your issue.
It's usage would reduce your script to:
$('.total').text($('.amount').sum());
You are converting the parseFloat into a string, then adding it to total. Only add .toFixed(2) to the final line, once things have been added.
var total = 0;
$(".amount").each(function() {
var value = $(this).val();
value = (value.length < 1) ? 0 : value;
var tmp = parseFloat(value);
total += tmp;
});
$(".total").text(total).toFixed(2);

Categories