Issue
I'm trying to change font-size and margin-bottom of a div element when scrolling using window.addEventListener('scroll', function(){}); and window.scrollY value. But I don't want it to change forever if I don't stop scrolling. I only want to reduce the font-size from 256px to about 192px and margin-bottom to about 128px. Can you guys please show me how to control it? Sorry I just started JS for couple days. Below is the part of my code.
let brownie = document.getElementById('backgroundBrownie');
window.addEventListener('scroll', function() {
let value = window.scrollY;
brownie.style.fontSize = 256 - value / 4 + 'px';
brownie.style.marginBottom = value + 'px';
})
<div class="background">
<div class="backgroundText" id="backgroundBrownie">
Brownie
</div>
</div>
Solution
Simply check the value you have computed with an if
and else if
statement.
At present, this seems quite jerky. I suspect your algorithm needs refining.
let brownie = document.getElementById('backgroundBrownie');
window.addEventListener('scroll', function() {
let value = window.scrollY;
let fontSize = 256 - value / 4;
if(fontSize < 192)
fontSize = 192;
else if(fontSize > 256)
fontSize = 256;
let marginBottom = value;
if(marginBottom > 128)
marginBottom = 128;
brownie.style.fontSize = fontSize + 'px';
brownie.style.marginBottom = marginBottom + 'px';
})
<div class="background">
<div class="backgroundText" id="backgroundBrownie">
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
Brownie<br />
</div>
</div>
Answered By - Lee Taylor
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.