Good day! The script processes the attribute with the translate property. How to change it to margin?

$(function() { var $win = $(window), $rev = $('[data-tr]'), winH2 = 0, winSt = 0; function reveal() { winSt = $win.scrollTop(); winH2 = $win.height()/2; $rev.each(function(i, el){ var y = el.getBoundingClientRect().top, toMiddleMax = Math.max(0, y-winH2), idealMarg = Math.min(+el.dataset.val, toMiddleMax), margMin = Math.min(idealMarg, idealMarg * (toMiddleMax/winH2)); $(this).css({transform: el.dataset.tr+"("+ margMin +"px)"}); }); } $win.on({ "load resize scroll" : reveal }); }); <div class="block" data-tr="translateX" data-val="300"></div> 
  • The above script does not handle the attribute with the translate property - Grundy
  • Why so? when <div class = "block" data-tr = "translateX" data-val = "300"> </ div> is indicated in the block, when scrolling the page, the value changes from 300 to 0. - LADYX
  • but in the code data-tr = "margin-left" - therefore the question is absolutely incomprehensible - Grundy
  • @Grundy Replaced. - LADYX
  • That is, you had a code that works with the margin, now you change it under the translate and ask how to change it under the margin? - Grundy

1 answer 1

The difference is to set the desired property.

To do this, change the following line

 $(this).css({transform: el.dataset.tr+"("+ margMin +"px)"}); 

margin-left is an immediate property, therefore it should be specified instead of transform , and the value, respectively, without using el.dataset.tr

As a result, for hard margin-left use you need it and specify

 $(this).css({"margin-left": margMin +"px"}); 

You can make a more general solution if you take the property name directly from the attribute

 $(this).css({[el.dataset.tr]: margMin +"px"}); 
  • yes, yes, yes, exactly what I need. That's how it is. Now I see my mistakes when I tried to make it myself. Thank you very much!!!! - LADYX
  • one
    @LADYX, for example, that IE cannot yet in ES6, and in computed properties . Just collect this object separately, and then just pass to the css method - Grundy
  • one
    @LADYX, var obj = {[name]: value} <=> var obj={}; obj[name]=value; var obj={}; obj[name]=value; - Grundy
  • one
    @LADYX, see the example in the comments above and find out what exactly is different from yours - Grundy
  • one
    @LADYX, well, if you look at my previous comment, you will see exactly this var obj={}; obj[name]=value; var obj={}; obj[name]=value; - Grundy