最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Script inside HTML is not executing with Angular 12 - Stack Overflow

programmeradmin0浏览0评论

Problem: I am trying to hide my navigation bar on scroll-down and show it on scroll-up. I placed my JavaScript to do this inside my HTML body at the bottom of the page, but it does not work. Any help is appreciated.

HTML(mainpageponent.html):

<body>
    <div class="flex" id="outercontainer">    
        <nav id="navbar">
            <a href="#" class="brand">Brand Name</a>
            <ul>
                <li class="active"><a href="#">Home</a></li>
                <li><a href="#about">About</a></li>
                <li><a href="#blogs">Services</a></li>
                <li><a href="#gallery">Contact</a></li>
            </ul>
        </nav>
        <div>
        //content
        </div>
<script type="text/javascript">
    var lastScrollTop = 0;
    navbar = document.getElementById("navbar");
    window.addEventListener("scroll",function(){
        var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        if(scrollTop > lastScrollTop){
            navbar.style.top="-80px";
        } else{
            navbar.style.top="0";
        }
        lastScrollTop = scrollTop;
    })    
</script>
</body>

CSS (mainpageponent.scss)

*{
    margin:0;
    padding:0;
    box-sizing: border-box;
    font-family: 'Montserrat', sans-serif ;
    scroll-behavior: smooth;
}
nav{
    position: fixed;
    top: 0;
    width: 100%;
    height: 80px;
    background:#607d8b;
    padding: 0 100px;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-items: center;
    transition: 0.5s;
}
ul{
    margin: 0;
    padding: 0;
    display: flex;
}
ul li{
    list-style: none;
}
ul li a{
    color: #fff;
    padding: 0 20px;
    font-size: 1.1em;
    text-decoration: none;
    font-weight: bold;
}
.brand{
    font-size: 1.8em;
    color: #fff;
    font-weight: bold;
    text-decoration: none;

}
body{
    font-family: Arial, Helvetica, sans-serif;
    background-color: #f6edd9;
    text-align: center;
    margin: 0;

    #sidebar{
    width: 10vw;
    height: 100vh;
    flex-direction: column;
    justify-content: flex-end;
    max-width: 80px;
    min-width: 30px;
    }

}

#banner{
    width: 100%;
    align-items: center;

    #nameimagecontainer{
    width: 60%;
    }

    #selfphotocontainer{
    width: 30%;
    }
}

#contentcontainer{
    font-size: 30px;
}
#getintouchbutton{
    font-style: normal;
}
#mainpagecontainer{
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;  

    #workcontainer{
        width: 100%;
        height: 100vh;
        background-color: green;
    }
    #servicescontainer{
        width: 100%;
        height: 100vh;
        background-color: red;
    }    

    #actioncontainer{
        width: 100%;
        height: 100vh;
        background-color: purple;
    }
    #contactcontainer{
        width: 100%;
        height: 100vh;    
        background-color: orange;
    }

}

So far, my script does nothing. Thank you.

Problem: I am trying to hide my navigation bar on scroll-down and show it on scroll-up. I placed my JavaScript to do this inside my HTML body at the bottom of the page, but it does not work. Any help is appreciated.

HTML(mainpage.ponent.html):

<body>
    <div class="flex" id="outercontainer">    
        <nav id="navbar">
            <a href="#" class="brand">Brand Name</a>
            <ul>
                <li class="active"><a href="#">Home</a></li>
                <li><a href="#about">About</a></li>
                <li><a href="#blogs">Services</a></li>
                <li><a href="#gallery">Contact</a></li>
            </ul>
        </nav>
        <div>
        //content
        </div>
<script type="text/javascript">
    var lastScrollTop = 0;
    navbar = document.getElementById("navbar");
    window.addEventListener("scroll",function(){
        var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        if(scrollTop > lastScrollTop){
            navbar.style.top="-80px";
        } else{
            navbar.style.top="0";
        }
        lastScrollTop = scrollTop;
    })    
</script>
</body>

CSS (mainpage.ponent.scss)

*{
    margin:0;
    padding:0;
    box-sizing: border-box;
    font-family: 'Montserrat', sans-serif ;
    scroll-behavior: smooth;
}
nav{
    position: fixed;
    top: 0;
    width: 100%;
    height: 80px;
    background:#607d8b;
    padding: 0 100px;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-items: center;
    transition: 0.5s;
}
ul{
    margin: 0;
    padding: 0;
    display: flex;
}
ul li{
    list-style: none;
}
ul li a{
    color: #fff;
    padding: 0 20px;
    font-size: 1.1em;
    text-decoration: none;
    font-weight: bold;
}
.brand{
    font-size: 1.8em;
    color: #fff;
    font-weight: bold;
    text-decoration: none;

}
body{
    font-family: Arial, Helvetica, sans-serif;
    background-color: #f6edd9;
    text-align: center;
    margin: 0;

    #sidebar{
    width: 10vw;
    height: 100vh;
    flex-direction: column;
    justify-content: flex-end;
    max-width: 80px;
    min-width: 30px;
    }

}

#banner{
    width: 100%;
    align-items: center;

    #nameimagecontainer{
    width: 60%;
    }

    #selfphotocontainer{
    width: 30%;
    }
}

#contentcontainer{
    font-size: 30px;
}
#getintouchbutton{
    font-style: normal;
}
#mainpagecontainer{
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;  

    #workcontainer{
        width: 100%;
        height: 100vh;
        background-color: green;
    }
    #servicescontainer{
        width: 100%;
        height: 100vh;
        background-color: red;
    }    

    #actioncontainer{
        width: 100%;
        height: 100vh;
        background-color: purple;
    }
    #contactcontainer{
        width: 100%;
        height: 100vh;    
        background-color: orange;
    }

}

So far, my script does nothing. Thank you.

Share Improve this question edited Sep 30, 2021 at 12:51 AloHA_ChiCken 4821 gold badge5 silver badges26 bronze badges asked Sep 30, 2021 at 8:25 Rudolph KritzingerRudolph Kritzinger 411 silver badge4 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 1

You could refer to this article on how to add scripts to the code.

However, I would not remend to do this. Angular removes all script tags from the code, and it is unmon practice to add scripts this way.

Much better approach would be to move the code in "script" tag into Your mainpage.ponent.ts into ngOnInit method.

add your scripts code inside your mainpage.ponent.ts

example://

constructor(){
   var lastScrollTop = 0;
        navbar = document.getElementById("navbar");
    window.addEventListener("scroll",function(){
        var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        if(scrollTop > lastScrollTop){
            navbar.style.top="-80px";
        } else{
            navbar.style.top="0";
        }
        lastScrollTop = scrollTop;
    })    
}

// or you can use lifecycle hook here

ngOnInit(){
   var lastScrollTop = 0;
            navbar = document.getElementById("navbar");
        window.addEventListener("scroll",function(){
            var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
            if(scrollTop > lastScrollTop){
                navbar.style.top="-80px";
            } else{
                navbar.style.top="0";
            }
            lastScrollTop = scrollTop;
        }) 
}

still i would remend Renderer2 or DOCUMENT injection token, you can read about them in angular documentation

constructor(@Inject(DOCUMENT) private document:Document){
}

@HostListener('scroll',['$event'])
onScrollHandler(e:Event){
let lastScrollTop = 0;
 const navbar = this.document.getElementById("navbar"); // you can use viewchild,renderer2 also

const scrollTop = this.document.defaultView.pageYOffset || this.document.documentElement.scrollTop;
            if(scrollTop > lastScrollTop){
                navbar.style.top="-80px";
            } else{
                navbar.style.top="0";
            }
            lastScrollTop = scrollTop;
}

ngOnInit(){

        }) 
}

Add your code inside the mainpage.ponent.ts file

The blog from Pavlo's answer worked for me.

In your case, first, you'd need to add a .js file to your project's assets folder which is present by default in Angular:

yourcode.js (assets/yourcode.js):

var lastScrollTop = 0;
navbar = document.getElementById("navbar");
window.addEventListener("scroll",function(){
    var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    if(scrollTop > lastScrollTop){
        navbar.style.top="-80px";
    } else{
        navbar.style.top="0";
    }
    lastScrollTop = scrollTop;
})    

Now your HTML file would look like this (you don't need to add script you'll see why):

HTML (mainpage.ponent.html):

<body>
<div class="flex" id="outercontainer">    
    <nav id="navbar">
        <a href="#" class="brand">Brand Name</a>
        <ul>
            <li class="active"><a href="#">Home</a></li>
            <li><a href="#about">About</a></li>
            <li><a href="#blogs">Services</a></li>
            <li><a href="#gallery">Contact</a></li>
        </ul>
    </nav>
    <div>
    //content
    </div>
</body>

Next you'd need to modify the ponent's typescript. Here you create a script DOM element, set the src and attach it to the DOM via renderer service, which is why you don't need the script tag inside the HTML file anymore.

You just have to add the path to your file which would be something like ../assets/yourcode.js. The code would look like this:

mainpage.ponent.ts

// 1. import dependencies
import { Renderer2, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';


// 2. pass then in constructor
constructor(
    private renderer2: Renderer2,
    @Inject(DOCUMENT) private _document
  ) {
  }


// 3. call them in ngOnInit
ngOnInit() {
   const s = this.renderer2.createElement('script');
   s.type = 'text/javascript';
   // the path to your script inside the assets folder '../assets/yourcode.js'
   s.src = 'https://path/to/your/script';
   s.text = ``;
   this.renderer2.appendChild(this._document.body, s);
}
发布评论

评论列表(0)

  1. 暂无评论