Ready Monetized Wordpress Website


Friday, May 31, 2019

How to implement an in place background change when scrolling?

I am on mobile; so, I apologize for not being able to show my source code but I have been trying different ways to change background image in place. What do I mean in place. In a typical scroll of full screen elements with different backgrounds, the effect is that the background is actually going upwards. I am trying to make it so that the background is being replaced from bottom to top. Essentially the height of the background of previous section is decreasing while the height of the next section is increasing, based on scroll position.

Here is what I have done so far.

  1. Create a container with 400% height of the viewport (400vh). This is because I have 4 elements in my “parallax” container. This way, the website will scroll based on page scroll.
  2. In each section, create an empty div with background color. This div has 100% width and 100% height. However, the divs are not visible because I used scaleY(0) by default.
  3. Now, based on scroll position, find which section is active and find the threshold (based on a 0-1 scale, scroll position in the page). This is how I calculate the position and get the threshold:

    const topPos = parallaxContainer.getBoundingClientRect().y + window.scrollY; const relativeScroll = window.pageYOffset - topPos; if (relativeScroll < 0) return; sections.forEach(s => { if (relativeScroll > s.offsetTop) { activeSection = s; } }); const threshold = ((relativeScroll % window.innerHeight) / window.innerHeight).toFixed(3); 

This threshold value is wrong. I can’t calculate it properly. I try to set scales for each background:

activeSection.querySelector(‘.bg’).style.transform = `scaleY(${1 - threshold})`; nextSection.querySelector(‘.bg’).style.transform = `scaleY(${threshold});` 

I dont even understand where the problem is. I check scale style property of background and it is somewhere in range of (0.01 - 0.09) instead of being (0.1 - 0.9). So, my backgrounds are consistently broken.

Could someone help me understand the issue here? Do you think it is possible to do this without knowing the active section? Basically set up a mathematical equation that calculated the background height automatically based on scroll position and heights of section (these values are all known to me)?

submitted by /u/GasimGasimzada
[link] [comments]

from web_design

No comments:
Write Your Comments

Ready Monetized Blogger Gaming Website