Jquery Hide When A Class Appears In Viewport
I would like to make a FIXED button dispear when a certain class apears in the ViewPort when scrolling down. To be more specific its a fixed Add-To-Cart button, it should disapear
Solution 1:
The new Intersection Observer API addresses your question very directly.
This solution will need a polyfill as Safari and Opera don't support this yet. (the polyfill is included in the solution).
In this solution, there is a box out of view that is the target (observed). When it comes into view, the button at the top in the header is hidden. It is shown once the box leaves the view.
Here is the code to solve your problem:
const buttonToHide = document.querySelector('button');
const hideWhenBoxInView = newIntersectionObserver((entries) => {
if (entries[0].intersectionRatio <= 0) { // If not in view
buttonToHide.style.display = "inherit";
} else {
buttonToHide.style.display = "none";
}
});
hideWhenBoxInView.observe(document.getElementById('box'));
header {
position: fixed;
top: 0;
width: 100vw;
height: 30px;
background-color: lightgreen;
}
.wrapper {
position: relative;
margin-top: 600px;
}
#box {
position: relative;
left: 175px;
width: 150px;
height: 135px;
background-color: lightblue;
border: 2px solid;
}
<scriptsrc="https://polyfill.io/v2/polyfill.min.js?features=IntersectionObserver"></script><header><button>NAVIGATION BUTTON TO HIDE</button></header><divclass="wrapper"><divid="box"></div></div>
Post a Comment for "Jquery Hide When A Class Appears In Viewport"