I'm in the process of converting a webpage that was originally designed using JS, HTML, and CSS into an Angular project. I have already included the JS file in index.html as shown below
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sample</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body class="">
<app-root></app-root>
<script type="text/javascript" src="assets/scripts/sample.js"></script>
</body>
</html>
sample.js
if (document.getElementById("fixedHeader")) {
window.onscroll = function () { fixedHeader(); };
var header = document.getElementById("fixedHeader");
var fixed = header.offsetTop;
}
function fixedHeader() {
if (window.pageYOffset > fixed) {
header.classList.add("fixed-active-lob");
$('body').addClass("fixed-nav");
} else {
header.classList.remove("fixed-active-lob");
$('body').removeClass("fixed-nav");
}
}
current.component.html
<div class="gb-nav gn">
<div id="fixedHeader" class="header">....
</div>
</div>
sample.css File included in styles.css having
.gb-nav.gn .fixed-active-lob {
position: fixed;
top: 0;
width: 100%;
z-index: 999999;
-webkit-box-shadow: 0px 10px 15px -1px rgba(0,0,0,0.45);
-moz-box-shadow: 0px 10px 15px -1px rgba(0,0,0,0.45);
box-shadow: 0px 10px 15px -1px rgba(0,0,0,0.45);
}
body.fixed-nav{
padding-top:56px
}
I encountered some issues trying to trigger the function from sample.js within the Angular component. However, I managed to achieve the desired result by redefining the same function in the
current.component.ts as:
@HostListener('window:scroll', ['$event'])
scrollHandler(event: any) {
console.log("Scroll event", event);
this.fixedHeader();
}
fixedHeader() {
var header = document.getElementById("fixedHeader");
var fixed: number = 0;
if (header?.offsetTop != undefined) {
fixed = header?.offsetTop;
} else {
fixed = 0;
}
if (window.pageYOffset > fixed) {
header?.classList.add("fixed-active-lob");
$('body').addClass("fixed-nav");
} else {
header?.classList.remove("fixed-active-lob");
$('body').removeClass("fixed-nav");
}
}
However, I would prefer to utilize the function from the JS file instead of duplicating it in the ts file, can anyone provide guidance on how to accomplish this?