Hi there!
I need to wait for elements with a specific selector to become visible. However, there are multiple elements on the page with the same selector(product cards), and I only want to wait for the elements that are currently within the viewport to become visible. I don't want to wait for the ones that are located further down the page. (the number of cards that are visible in the viewport will vary)
Any suggestions or code examples would be greatly appreciated.
This thread is trying to answer question "How can I wait for elements with a specific selector that are currently within the viewport to become visible, while ignoring those that are located further down the page?"
I attempted the solution provided in this GitHub link (https://github.com/microsoft/playwright/issues/8740), but unfortunately, it didn't work for me. If someone has successfully implemented it, I'd greatly appreciate the opportunity to take a look. Thank you!
@skorp32 The elements underneath aren't necessarily hidden; they're just out of view. But all the cards share the same common element name, so it waits for all the elements to become visible. However, this isn't necessary in my case. I only want to wait for the cards that are currently visible in the viewport, which could be four, five, or even just one, depending on the card size
Finally have a working solution in case anyone visits the thread
const elementCount = await page.evaluate((elementName) => {
const viewport = {
top: window.scrollY,
bottom: window.scrollY + window.innerHeight,
left: 0,
right: window.innerWidth,
};
const elements = Array.from(document.querySelectorAll(`${elementName}`));
const elementsInsideViewport = elements.filter((element) => {
const elementRect = element.getBoundingClientRect();
return (
elementRect.top < viewport.bottom &&
elementRect.bottom > viewport.top &&
elementRect.left < viewport.right &&
elementRect.right > viewport.left
);
});
return elementsInsideViewport.length;
}, elementName);
console.log(`Number of elements with the name "${elementName}" in the viewport: ${elementCount}`);
Another way i've found is using a count(). While it sounds what you are doing has additional rules like "Is locator/element visible", so you will be force to iterate the elements matched and from here can create your specific rules... Nice thing got my stuff like this, i was able to talk my developers into adding specific attribute for different "groups" where i may need to "Do the hocky pocky..." Nice thing if you locator count returns 0 that can be useful, quick and handy at times too...
Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].