skip to Main Content

I’ve made a function that accepts an id then reveals the element associated with that id. I want this function to be used for the html attribute onclick, but I have been having problems with it not being able to find the function returning the error below when clicked on.

Reference Error of the html attribute on click

And this is how the onclick attribute look
<button onclick="revealOnClick('SomeTypeofID')"><a style="font-size: 4vw;">Sometype of Button<a></button>

The function is within a javascript file

export function revealOnClick (id = '') {     document.getElementById("id").style.removeProperty("display"); }

that is imported into another javascript file

import {Panel, revealOnClick} from "./JS_Module/websitemodule.js";

then I import the javascript file into the html

<script defer type="module" src="index.js"></script>

However it still seems to not be able to find it.

I’ve tried moving around the <script defer type="module" src="index.js"></script>, it ‘s currently on top in the head, but I’ve removed the "defer" and put it at the bottom below the head, thinking it wasn’t able to laod the javascript, but that didnt work.

I’ve tried moving the code below into the javascript file it was importing to and removed the export, but that also didn’t work.

export function revealOnClick (id = '') {     document.getElementById("id").style.removeProperty("display"); }

I’ve also tried adding the type="button" thinking it could be the submit and then after I’ve tried moving the onclick to the anchor tag, but both didn’t work

<button><a style="font-size: 4vw;" onclick="revealOnClick('SomeTypeofID')">Sometype of Button<a></button>

2

Answers


  1. Scripts with type of module do not register global variables (on window object). You need to assign it manually in the websitemodule.js (also, remove quotes in your document.getElementById(id) function call):

    export function revealOnClick(id = '') {
      document.getElementById(id).style.removeProperty('display');
    }
    
    window.revealOnClick = revealOnClick;
    

    FYI, el.style.removeProperty() only removes inline styles. If the display property is defined in a CSS file, you need to overwrite it but not to remove it:

    document.getElementById(id).style.display = 'block';
    
    Login or Signup to reply.
  2. If a function exists in a file at a different path, the src of the script must follow the path to that file.

    <script type="module" src="./JS_Module/websitemodule.js"></script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search