简体   繁体   中英

How to use client side functionality on EJS page

After spending a few hours, I could not figure out the best practise to use the 'client-side' functionality on EJS page. The scenario is stated below:

  1. I am using express (NodeJS) and using the EJS to render the Landing page (along with the other functionality). Initially, I was struggling to use JQuery but I manage to require it to the 'app.js' (definitely, not the best practice but could not find alternative solution hence this question). So, coming to the original question. I want to use some the client-side scripting on the EJS page but as that page has server-side code not entirely sure how to use client side scripting on it (JQuery/Javascript, i,e. on scroll do that etc.).
  2. My header.ejs file contains some menu items which I want to be dynamic, ie top menu bar to be sticky but as that navbar is in the header.ejs file not sure how can I do that from client-side. Currently, I could not call that do that from the one EJS file to another EJS, see below.
    // Sticky bar
    window.onscroll = function() {myFunction()};

    var navbar = document.getElementById("navbar");
    var sticky = navbar.offsetTop;

    function myFunction() {
      if (window.pageYOffset >= sticky) {
        navbar.classList.add("sticky")
      } else {
        navbar.classList.remove("sticky");
      }
    }

When you use js files in ejs, it is like you don't use ejs or nodejs. It's just static files. And you can't use npm package.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM