0

I am making a chrome extension and I want to add an overlay navigation, but I need Javascript for that, and when I put the Javascript in, chrome told me I cannot use inline JS.

So then I used an event listener, but then it told me that it cannot read the even listener.

The navigation's HTML:

<div id="Navigation" class="Overlay">
    <a href="javascript:void(0)" id="closebtn">&times;</a>
    <div class="Links">
        <a href="popup.html"> Home </a>
        <a href="colors.html"> Colors </a>
        <a href="links.html"> Links </a>
    </div>
</div>
<span id="menuIcon">
    <div class="menuPart"></div>
    <div class="menuPart"></div>
    <div class="menuPart"></div>
</span>

The navigation's EventListener (the JS):

document.getElementById("menuIcon").addEventListener("click", function(){
document.getElementById("Navigation").style.width = "100%"
});

document.getElementById("closebtn").addEventListener("click", function(){
document.getElementById("Navigation").style.width = "0%"
});

I have no idea what I'm doing wrong. Please help me.

YSUF_Z
  • 1
  • 2

1 Answers1

0

In a Chrome extension, you should use an external JavaScript file to add event listeners and manipulate the DOM.

Create a new JavaScript file, and name it something like overlay_nav.js or whatever you'd prefer.

Paste your JavaScript code into the .js file like the following example:

// overlay_nav.js 
document.getElementById("menuIcon").addEventListener("click", function(){ 
enter code heredocument.getElementById("Navigation").style.width = "100%"; 
}); 

document.getElementById("closebtn").addEventListener("click", function(){ 
document.getElementById("Navigation").style.width = "0%"; });

Now you'll be able to link the .js file using a tag before the closing tag. See the example below:

<!-- popup.html or your relevant HTML file -->
<!DOCTYPE html>
<html>
<head>
    <!-- Your other HTML head content goes here -->
</head>
<body>
    <!-- Your navigation and menu icon HTML goes here -->

    **<!-- Add the .js file here -->
    <script src="overlay_nav.js"></script>**
</body>
</html>

Note that you'll have to place the .js script in the same folder as the .html script

haris.doku
  • 36
  • 4
  • Do I add the in the or ? – YSUF_Z Jul 20 '23 at 22:34
  • The following: should be added in the body and not the head. But I would suggest trying both (head and body) just to see how each option works out. I tend to work this way since you'll learn more from your mistakes. In programming, trial & error is the best method to learn. That is if you're interested in learning :) – haris.doku Jul 20 '23 at 23:14