jquerysetintervaldetecttranslate3d

If element translate 3d ... addClass


how can I write a script that does this?

If the div class "test" has the property translate3d (0px, 100px, 0px) add to this the "active" class else remove it.

I tried something like this but it's not right ...

setInterval(function(){
  if($('.test').css('transform') == 'translate3d(0px, 100px, 0px)') {
    $('.test').addClass('active');
  } else {
    $('.test').removeClass('active');
  }
}, 1);

Solution

  • You need to do it like below using regex match:-

    $(document).ready(function(){
      $('.test').each(function(){
        console.log($(this).css('transform') == 'matrix(1, 0, 0, 1, 0, 100)');
        if($(this).css('transform') == "matrix(1, 0, 0, 1, 0, 100)"){
          $(this).addClass('active');
        } else {
          $(this).removeClass('active');
        }
      });
    });
    .active {
      color: red;
      font-size: 20px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="test" style="transform:translate3d(0px, 100px, 0px)">Hello</div><br/><br/>
    <div class="test" style="transform:translate3d(10px, 10px, 100px)">Hello</div>

    Note:- check the console.log() value and you will see it's a matrix

    Reference Taken:- Get translate3d values of a div?

    To check any element have transform property or not use below regex:-

    /matrix(?:(3d)\(\d+(?:, \d+)*(?:, (\d+))(?:, (\d+))(?:, (\d+)), \d+\)|\(\d+(?:, \d+)*(?:, (\d+))(?:, (\d+))\))/)