How to add percentages in Javascript

I'm trying to make a slider by adding 100% to each image but can not get it done. My main question is how to add the percentages. I tried console.log(100% + 100%) just for an example and it does not work either. Thanks for any suggestions.

<section class="slider">
<img class="img" id="img1" src="girl.jpg" alt="" style="left: -100%">
<img class="img" id="img2" src="sport.jpg" alt="" style="left: 200%" >
<img class="img" id="img3" src="biceps.jpg" alt="" style="left: 100%" >
<img class="img" id="img4" src="weights.jpg" alt="" style="left: 0%">
</section>

javascript

var img = document.getElementsByClassName('img');

function slide() {
for(i=0; i < img.length; i++) {
img[i].style.left += "100%";
console.log(img[i].style.left);

 }
}

1 answer

  • answered 2018-01-11 19:52 Marcelo Myara

    You can't because this attribute's value is not a number (it's a text). So here's what you can do: Try to parse the text to get only the number portion, parse it into an integer, do the math, then turn it back to a string. Something like

    let tempPercent = parseInt(img[i].style.left.replace('%', ''), 10); tempPercent += 100; img[i].style.left = tempPercent+'%';