3

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;
});
Sergi
  • 1,192
  • 3
  • 19
  • 37
  • 3
    You need to treat `firstPostOrder` as an integer using `parseInt()` before doing arithmetic. Otherwise, you're just appending `1` to a string. – BenM Aug 23 '18 at 13:22

4 Answers4

7

Css properties are strings, and '1' + 1 = 11.

Add "+" before firstPostOrder to convert it to a number.

firstPost.style.order = +firstPostOrder += 1;

Programmer
  • 1,973
  • 1
  • 12
  • 20
2

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

DavidB
  • 2,566
  • 3
  • 33
  • 63
1

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;
});
Arun Kumar
  • 885
  • 5
  • 11
  • Always suggest `radix` with `parseInt` i.e. `parseInt(firstPostOrder, 10)` see https://stackoverflow.com/questions/6611824/why-do-we-need-to-use-radix – Satpal Aug 23 '18 at 13:25
  • That is just not working. The order is not changing at all. – Sergi Aug 23 '18 at 13:28
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 "+=".

Cernael
  • 91
  • 5