1

I was following a YouTube tutorial for a Javascript Image Slider, and I came across this line of code that I'd like to better understand so that I can effectively modify it to suit my website's needs.

Here's the line:

carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';

  1. carouselSlide is what contains all of the images in the image slider.

  2. size is the width of a single image (they are all the same width).

  3. counter increases each time a button is pressed.

The main source of my confusion is how everything is concatenated. I don't quite understand why the two single quotes are necessary inside of the translateX argument (and why they're positioned where they are), nor do I understand why the plusses are necessary.

Could someone help me understand the syntax?

Alex Viar
  • 21
  • 3

1 Answers1

1

'translateX(' + (-size * counter) + 'px)' is constructing a string using fixed text and the values from the size and counter variables. Quotes are added around the fixed text and + is required to add bits of the string together into a single string.

'translateX(' - a fixed string

+ - a concatenator

(-size * counter) - calculate a value from variables

+ - a concatenator

'px)' - a fixed string

Thus, once the calculation has been done, and if we assume that equated to 100:

'translateX(' + 100 + 'px)'

which is joined together to get:

'translateX(100px)'

It may look confusing because + is usually used for addition - but, it is also be used to concatenate strings.

ATD
  • 1,344
  • 1
  • 4
  • 8