Reputation: 21
So when I try to run my html file in the browser chrome logs that error, but in visual studio code it doesn't register any problems. How can i fix this and ensure it doesn't happen in the future? My js code:
const navbarBtn = document.querySelector("navbar__btn");
const navbarLinks = document.querySelector("navbar__links");
navbarBtn.addEventListener("click", function () {
let value = navbarLinks.classList.contains("navbar__collapse");
if (value) {
navbarLinks.classList.remove("navbar__collapse");
} else {
navbarLinks.classList.add("navbar__collapse");
}
});
Upvotes: 1
Views: 359
Reputation: 248
There are two things potentially wrong with your code.
You need to make sure your JS is loaded after the required html is loaded. Without going in detail two good methods for that are:
loading the script at the bottom of the html file
<script src="main.js"></script>
</body>
Using defer
on your script
<script defer src="./main.js"></script>
</head>
In your example you are trying to access your DOM elements like this:
const navbarBtn = document.querySelector("navbar__btn");
However, this is looking for a custom tag <navbar__btn>
. I believe it is more likely that you are looking for a tag with the class of "navbar__btn" so you have to add a point to refer to a class.
const navbarBtn = document.querySelector(".navbar__btn");
Upvotes: 2
Reputation: 414
The problem is, it is not finding the node that you are trying to attach the event to. So it has to be associated to the working of the document.querySelector()
method.
You might want to send an id
or class
of the node, but this is not the right way to pass values of id
and class
.
You should rewrite you code as
// If you are passing id
const navbarBtn = document.querySelector("#navbar__btn");
const navbarLinks = document.querySelector("#navbar__links");
// If you are passing class
const navbarBtn = document.querySelector(".navbar__btn");
const navbarLinks = document.querySelector(".navbar__links");
Remember you will get the first element in case you have passed class
as argument.
Upvotes: 0
Reputation: 2603
For a jquery code to run, it must always be enclosed within $(), which you have missed in navbarBtn.addEventListener("click", function () {
Try this:
const navbarBtn = document.querySelector("navbar__btn");
const navbarLinks = document.querySelector("navbar__links");
$(navbarBtn).addEventListener("click", function () {
let value = navbarLinks.classList.contains("navbar__collapse");
if (value) {
navbarLinks.classList.remove("navbar__collapse");
} else {
navbarLinks.classList.add("navbar__collapse");
}
});
Also, you really don't need to the addEventListener function as Jquery automatically detects if you click on a button.
This code should also work:
$(navbarBtn).on('click,function(){
// your logic here
});
Upvotes: 0