I'm trying to implement a sticky header for my table in Angular 5.
these are the links I reffered. https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_navbar_sticky
I need something similar to this but my usage is I'm placing the scrollable content in a Scrollable div. hence my on scroll values remain same they wont change. I'm able to trigger the onscroll event
`<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="body">
<div class="header">
<h2>Scroll Down</h2>
<p>Scroll down to see the sticky effect.</p>
</div>
<div id="navbar">
<a class="active" href="javascript:void(0)">Home</a>
<a href="javascript:void(0)">News</a>
<a href="javascript:void(0)">Contact</a>
</div>
<div class="content">
<h3>Sticky Navigation Example</h3>
<p>The navbar will stick to the top when you reach its scroll position.
</p>
<p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum
definitiones no quo, maluisset concludaturque et eum, altera fabulas ut
quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert
laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no
molestiae voluptatibus.</p>
<p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum
definitiones no quo, maluisset concludaturque et eum, altera fabulas ut
quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert
laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no
molestiae voluptatibus.</p>
</div>
</div>
<script>
window.onscroll = function() {myFunction()};
var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;
var navbar1 = document.getElementsByClassName("body");
var sticky1 = navbar1[0].offsetTop;
function myFunction() {
console.log("01 --> " + sticky1);
console.log("02 --> " + window.pageYOffset);
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
}
</script>
</body>
</html>`
this is how my code is.
I used this link to convert the JS code to NG2
here is a Sandbox with an example that should work pretty much everywhere. In the example that is shown in the demo, I'm using a directive that is responsible for setting the position:fixed
property on the navbar and appropriate margin-top
on the content, so that the content is not overlapped, in the moment of 'fixation'.
You can also check out the position:sticky
css property, but it wont work in some older browser. I hope this is helpful :)