1

In onclick function showing a error canot set property of null , this used for navigation bar

const body = document.querySelector("body");
const navbar = document.querySelector(".navbar");
const menuBtn = document.querySelector(".menu-btn");
const cancelBtn = document.querySelector(".cancel-btn");
menuBtn.onclick=()=>{
  navbar.classList.add("show");
  menuBtn.classList.add("hide");
  body.classList.add("disabled");
};
cancelBtn.onclick=()=>{
  body.classList.remove("disabled");
  navbar.classList.remove("show");
  menuBtn.classList.remove("hide");
};
window.onscroll=()=>{
  this.scrollY > 20
    ? navbar.classList.add("sticky")
    : navbar.classList.remove("sticky");
};

  • 2
    Please also show your HTML... it seems like the menuBtn or cancelBtn don't exist. – Acidic9 Mar 14 '21 at 06:48
  • Don’t use `.onclick`, `.onscroll`, etc. Use [`.addEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) instead. Instead of your `body` variable simply use `document.body`. Instead of the `scroll` event use CSS `@media` queries, or at least instead of the conditional operator, use [`navbar.classList.toggle("sticky", scrollY > 20);`](https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/toggle). – Sebastian Simon Mar 14 '21 at 07:00
  • Is your ` – Sebastian Simon Mar 14 '21 at 07:00
  • probably you are loading your script in the head of your html document, thus, the DOM elements do not exist yet. Either use `defer` or place the ` – derpirscher Mar 14 '21 at 08:08
  • Does this answer your question? [TypeScript cant read property addEventListener](https://stackoverflow.com/questions/66549448/typescript-cant-read-property-addeventlistener) – derpirscher Mar 14 '21 at 08:08
  • Please put up a complete example which shows the error and is in a Stackoverflow snippet otherwise we start guessing what the problem is. Also, your dev tools will show you which line has the error. – A Haworth Mar 14 '21 at 09:18
  • @AHaworth _“Also, your dev tools will show you which line has the error. ”_ — The line number is already included in the title: it’s the line with `menuBtn.onclick`. – Sebastian Simon Mar 14 '21 at 09:30

0 Answers0