Reputation:
What I'm trying to do is display an array (which repeats itself endlessly) in the browser. However, even though I can determine from the console.logs
that the array is looping properly, what is ultimately being displayed in the browser isn't reflecting this and instead acting abnormally. Here is a Fiddle. Below is the code, an explanation of what I believe is happening, and one of my failed attempts to resolve the issue.
<div id="listings-container">
<div class="listing" id="one"></div>
<div class="listing" id="two"></div>
<div class="listing" id="thr"></div>
<div class="listing" id="fou"></div>
<div class="listing" id="fiv"></div>
<div class="listing" id="six"></div>
<div class="listing" id="sev"></div>
<div class="listing" id="eig"></div>
</div>
var listingClass = document.getElementsByClassName('listing');
var listingsArray = [];
var listingsContainer = document.getElementById('listings-container');
var moveOne = window.innerHeight / 3;
var oneThird = window.innerHeight / 3;
for (var i = 0; i < listingClass.length; i++) {
listingsArray.push(listingClass[i]);
};
listingsContainer.addEventListener('scroll', test);
function test(){
var first = listingsArray[0];
if (listingsContainer.scrollTop >= moveOne) {
moveOne += oneThird;
listingsArray.shift();
listingsArray.push(first);
listingsContainer.removeChild(first);
listingsContainer.appendChild(first);
console.log(listingsArray);
};
console.log(listingsArray);
};
What's happening is that, as you scroll down, every other listing
(i.e. two
, fou
, six
, etc.) is being jumped over, so to speak, once the top of the element reaches the top of the browser. The reason this is happening, I believe, is because each listing
is shifted upwards one spot, so I've tried adding the following code (which, for whatever reason, behaves exactly as it would without it).
#listings-container:first-child {
height: 33.33vh; /* same height as listings class */
}
var spacer = document.createElement('div');
listingsContainer.insertBefore(spacer, first);
I'm at a loss. Please help!
Upvotes: 2
Views: 66
Reputation: 95
You have the visual combination of 2 effects there:
- the regular scrolling
- the statements "listingsContainer.removeChild()" and "listingsContainer.appendChild()
As a result once the regular smooth scrolling has reached one third of the window height, the display jumps by an additional one third.
I am not exactly sure what you are trying to accomplish. You may need to scroll back by one third once you have removed and appended the first child.
If this is the case, use scrollBy() or scrollTo() to achieve the desired effect.
Upvotes: 1