I was trying to build a portfolio for mobile device but I got some problem in my CSS and Js code which I linked to the HTML via link. Most of the CSS works fine but js doesn’t run a bit. I have my 3 files* (html, css & js) in a folder.
When I set “display-flex” clsss is the CSS code externally, id didn’t run with Js.
Talking about my js which I linked to the HTML, it didn’t work. When I add a onclick function in the external js code, I got an* error which was something like ” Uncaught TypeError: Cannot read property ‘addEventListener’ of null “. So I had to remove the js link and directly write it in the HTML
Here is the HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Page title</title>
<link rel="stylesheet" href="style.css">
<script src="script.js" type="text/javascript" charset="utf-8"></script>
<style type="text/css" media="all">
.display-flex{
display: flex;
height: 5vh;
}
</style>
</head>
<body>
<header>
<div class="inner-header">
<div class="main-logo-area center-box">
Abdullah
</div>
<div class="menu-area center-box">
<button id="menu-button">Menu</button>
</div>
</div>
</header>
<ul class="menu-elements center-box">
<li><a href="#Home">Home</a></li>
<li><a href="#About Me">About Me</a></li>
<li><a href="#Contract Me">Contract Me</a></li>
<li id="dark-mode-switch">Dark Mode</li>
</ul>
<script type="text/javascript" charset="utf-8">
let menu_button = document.getElementById("menu-button");
let menu_elements = document.querySelector(".menu-elements");
menu_button.onclick = ()=> {
menu_elements.classList.toggle("display-flex");
console.log(menu_elements)
}
</script>
</body>
</html>
CSS:
*{
background-color: #00ccff3c;
box-sizing: border-box;
margin: 0;
padding: 0;
list-style: none;
overflow: hidden;
}
.center-box {
display: flex;
justify-content: center;
align-items: center;
}
.display-none {
display: none;
}
.display-flex {
display: flex;
}
.display {
display: block;
}
header {
width: 100vw;
height: 10vh;
display: flex;
justify-content: space-around;
}
.inner-header {
width: 95vw;
display: flex;
justify-content: space-between;
}
.main-logo-area {
color: #dbe4e6;
}
.menu-area button {
}
.menu-elements {
justify-content: space-around!important;
height: 0vh;
display: none;
}
And the Js:
let menu_button = document.getElementById(“menu-button”);
let menu_elements = document.querySelector(“.menu-elements”);
menu_button.addEventListener(“click”, (e)=>{
alert(“heijj”)
})
So, how am I suppose to fix those issues. I have this problem over and over again. I just don’t know what I have done wrong.
Reyz Knight is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.