Home > database >  Positioning of element with JS transform properties (CSS get's overwritten by JS)
Positioning of element with JS transform properties (CSS get's overwritten by JS)

Time:10-13

I'm trying to position two images on top of eachother, and having one of them rotate on scroll while the other one is not rotating - which works, except i'm unable to position and scale my elements in my CSS. As soon as i start scrolling, the image with the JS jumps into the corner while the other one remains where it is. I believe it's because my JS overwrites my CSS properties, but is there any way of working around this? Can i position my two elements while maintaining my JS?

var elem = document.getElementById("rotatelogo");
window.addEventListener('scroll', function() {
    var value = window.scrollY * 0.25;
    elem.style.transform = `translatex(-50%) translatey(-50%) rotate(${value}deg)`; 
});
body {
  height: 200vh;
  background: darkblue;
}

.guide {
  width:150px;
  height:150px;
  margin-top:50px;
  margin-bottom:-300px;
  margin-left:50px;
}
<div class="guide" style="position:relative">
    <img src="http://jakobnatorp.com/wp-content/uploads/2021/10/ARROW.png" style="position:fixed;"/>
    <img class="portfolio" id="rotatelogo" src="http://jakobnatorp.com/wp-content/uploads/2021/10/SELECTED-WORK-BEIGE.png" style="position:fixed"/>
</div>

CodePudding user response:

Remove translate from your code.

var elem = document.getElementById("rotatelogo");
window.addEventListener('scroll', function() {
    var value = window.scrollY * 0.25;
    elem.style.transform = `rotate(${value}deg)`; 
});
body {
  height: 200vh;
  background: darkblue;
}

.guide {
  width:150px;
  height:150px;
  margin-top:50px;
  margin-bottom:-300px;
  margin-left:50px;
}
<div class="guide" style="position:relative">
    <img src="http://jakobnatorp.com/wp-content/uploads/2021/10/ARROW.png" style="position:fixed;"/>
    <img class="portfolio" id="rotatelogo" src="http://jakobnatorp.com/wp-content/uploads/2021/10/SELECTED-WORK-BEIGE.png" style="position:fixed"/>
</div>

CodePudding user response:

I am not sure what you want to achieve by usingtranslatex(-50%) translatey(-50%), but this is causing the images center to be positioned on the top left corner of the parent element. If you just use elem.style.transform = `rotate(${value}deg)`; it will rotate in place.

  • Related