Is there a way to dynamically hide button B when the user scrolls and button A becomes visible on the screen? Additionally, how can we show button B again once button A is no longer visible to the user? Both buttons should never be visible simultaneously.
Here is what I have set up so far:
On an online store's cart page, there is a Go To Checkout button that appears in the middle of the page as the user scrolls to that section. This button, identified as button A in the code snippet below:
<div id="horizontalCheckoutBottomPageButtonA"> <div class="cart-section"> <button id="CheckOutA" class="button button--regular" type="submit" name="checkout" form="cart">Go To Check Out></button>
There is also a sticky checkout button, button B, which remains on the page and follows the user as they scroll. It is represented by the following code:
<div id="horizontalCheckoutBottomPageButtonB" <div class="container--large container--vertical-space"> <button id="CheckOutB" class="button button--regular button--outline sticky-buttonzzz" type="submit" name="checkout" form="cart">Check Out ></button</div</div>
I've attempted to implement a script that currently logs whether button A is visible or not. However, it always indicates that button A is visible even when it's scrolled out of view. The desired logic I aim for is:
1. Hide button B when button A becomes visible to the user on the screen as they scroll.
2. Un-hide button B when button A is no longer visible to the user scrolling on the screen.
Please refer to the JavaScript code provided below, which is only logging "The ButtonA is visible in the viewport", requiring adjustments to achieve the intended functionality:
<script>
function isInViewport(el) {
const rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
const CheckOutA =
document.querySelector('#CheckOutA');
const message = document.querySelector('#message');
document.addEventListener('scroll', function () {
const messageText = isInViewport(CheckOutA) ?
'The ButtonA is visible in the viewport' :
'The ButtonA is not visible in the viewport';
message.textContent = messageText;
}, {
passive: true
});
</script>