Hi I have a list of Li elements with overflow hidden, I just want to find the last visible Li on screen let say a element which is closest to right
Loading
Hi I have a list of Li elements with overflow hidden, I just want to find the last visible Li on screen let say a element which is closest to right
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Uday DodiyaRank #239 · 10.3K reputationPosted Jan 9, 2023, 11:14 PM EST
Answer By ChatGPT
You can use JavaScript to determine the visibility of each
lielement and then find the one that is closest to the right edge of the screen. Here's an example of how you might do this:var listItems = document.querySelectorAll('li'); var lastVisibleItem; var minDistance = Infinity; for (var i = 0; i 0 && rect.left < window.innerWidth) { // The element is visible on the screen var distance = rect.right - rect.left; if (distance < minDistance) { minDistance = distance; lastVisibleItem = listItems[i]; } } } // lastVisibleItem is the last visible li elementThis code iterates through all of the
lielements, checks to see if they are visible on the screen (based on their bounding rectangle), and then finds the one that is closest to the right edge of the screen.Uday DodiyaRank #239 · 10.3K reputationPosted Jan 9, 2023, 11:17 PM EST
Another Solution
Here's one way you could do this using JavaScript:
Get the
lielements that are visible on the screen by using thegetClientRectsmethod on each element. This method returns a list of rectangles that represent the element's size and position relative to the viewport.Iterate through the list of visible
lielements and find the one that is closest to the right edge of the viewport. You can do this by comparing therightproperty of each element's rectangle to the width of the viewport. The element with the highestrightvalue is the one that is closest to the right edge.Here's some example code that demonstrates how this could work:
const liElements = document.querySelectorAll('li'); // Find the last visible li element let lastVisibleLi; let maxRight = 0; for (const li of liElements) { const rect = li.getClientRects()[0]; if (rect.right > maxRight) { maxRight = rect.right; lastVisibleLi = li; } } console.log(lastVisibleLi); // The last visible li elementThis code will find the last visible
lielement by iterating through all of thelielements and keeping track of the one with the highestrightvalue.