Issue
Short Description:
I want to select an element based on it's position on the viewport.
Example use-case:
for example consider the below image. When I navigate with keyboard, I want to move to Block D after Block A in mobile viewport. But which block is placed below Block A is not fixed. It can change based on the gap below Block A, or if additional blocks come in to picture (say Block E), then it might come below Block A.
Question:
Is there a way to select a block/element which is placed below Block A or any of the blocks for that matter.
p.s. Again, I am aware of selecting via class names & navigating via DOM Order. But need help to navigate dynamically placed elements.
Solution
Suppose your page is structured like this:
- Gap between the top of the page and the top of Block A : 10px
- Block A height: 100px
- Gap between the bottom of Block A and the next Block (via margin-bottom for example): 10px
So the distance between the top of the document and the top of the unknown block after Block A is 120px. we call it "secondBlockDistanceFromTop".
Now you have to get a list of all possible blocks after Block A, you could do that by giving all of them a ".block" class and use "document.querySelectorAll". We store this array in "blocks" variable.
Every DOM object's distance from the top of the document can be calculated by this formula:
let blockDistanceFromTop=el.getBoundingClientRect().top + window.scrollY
now you can use an array iteration method on the "blocks" array and check if each element's "blockDistanceFromTop" equals "secondBlockDistanceFromTop"
Answered By - Erfan

0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.