Search code examples
javascriptjqueryhtmltransformtranslate

Increment each of X value of transform attr by 50


I am trying to increment the transform translate X value of each of the images by 50. I am able to do that with the width. Is there anyways I can do that with the the transform translate X value

Expected Result:

transform="translate(64.5,0)
transform="translate(114.5,0)
transform="translate(164.5,0)

This is my code to increment each of the width:

HTML:

<img src="http://lorempixel.com/400/200" class="what-can-we-do-tash">
<img src="http://lorempixel.com/400/200" class="what-can-we-do-tash">
<img src="http://lorempixel.com/400/200" class="what-can-we-do-tash">
<img src="http://lorempixel.com/400/200" class="what-can-we-do-tash">
<img src="http://lorempixel.com/400/200" class="what-can-we-do-tash">

Javascript/jQuery:

$('.what-can-we-do-tash').css('width', function(i){
   return $(this).width() + (i * 50);
});

Can I do something similar for transform translate value.


Solution

  • This should do it:

    $('.what-can-we-do-tash').css('transform', function(i, s) {
       return s.replace(/(\d+)(\.\d+)?(, ?\d+\))/, (s, t, u, v) => `${parseFloat(t + u) + 50 * (i + 1)}${v}`)
    });
    .what-can-we-do-tash {
      transform: translate(100.5px ,0);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <img src="http://lorempixel.com/400/200" class="what-can-we-do-tash">
    <img src="http://lorempixel.com/400/200" class="what-can-we-do-tash">
    <img src="http://lorempixel.com/400/200" class="what-can-we-do-tash">
    <img src="http://lorempixel.com/400/200" class="what-can-we-do-tash">
    <img src="http://lorempixel.com/400/200" class="what-can-we-do-tash">