A template literal will not recognize an imported function

import {createTasks} from './app.js';


document.addEventListener("DOMContentLoaded", function () {       

 function showNewTaskModal () {

        newTaskModal.classList.add('show');

        const html = `
            <div id="rowrow">
                <input type="text" placeholder="New Task"></input>
                <input type="text" placeholder="Add description"></input>
                <div id="row22">
                    <button>
                        <img src="./Icons/clock.png">
                    </button>
                    
                    <button>
                        <img src="./Icons/star_empty.png">
                    </button>

                    <button onclick="createTasks()">
                        Save
                    </button>
                </div>
            </div>
        `;
    
        newTaskModal.innerHTML = html;

        document.body.appendChild(newTaskModal);
    }
}

The createTasks() function is not recognized within the HTML template literal and leads to a reference error when clicked on the button. The solution that works is to add the HTML to the DOM first, then add an event listener to the button.

Error message: index.html:1 Uncaught ReferenceError: createTasks is not defined at HTMLButtonElement.onclick (index.html:1:1) onclick @ index.html:1

Answer №1

One of the main benefits of using modules in programming is that they create a scoped environment. This means that functions with similar names in different modules won't clash with each other:

JavaScript modules have their own distinct scope separate from the global scope. This separation ensures that variables, functions, and other code defined within a module are isolated from code in other modules or the global scope unless explicitly exported. Such isolation helps in avoiding naming conflicts and enhances code organization and reusability.

To use any functionality from a module outside of it, you must explicitly export it. Alternatively, you can also add it to the global scope using the following approach:

import {performTasks} from './app.js';

window.performTasks = performTasks;

document.addEventListener("DOMContentLoaded", function () {       

 function displayNewTaskModal () {

        newTaskModal.classList.add('show');

        const html = `
            <div id="task-row">
                <input type="text" placeholder="New Task"></input>
                <input type="text" placeholder="Add description"></input>
                <div id="task-buttons">
                    <button>
                        <img src="./Icons/clock.png">
                    </button>
                    
                    <button>
                        <img src="./Icons/star_empty.png">
                    </button>

                    <button onclick="performTasks()">
                        Save
                    </button>
                </div>
            </div>
        `;
    
        newTaskModal.innerHTML = html;

        document.body.appendChild(newTaskModal);
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is the DOMContentLoaded event connected to the creation of the DOM tree or the rendering tree?

After profiling my app, I noticed that the event is triggered after 1.5 seconds, but the first pixels appear on the screen much later. It seems like the event may only relate to DOM tree construction. However, this tutorial has left me feeling slightly con ...

Discover the nearest locations along your route using Google Maps API V3's boundary feature

I am trying to find locations that fall within a specific boundary along a route. I need the results to be ordered by distance from the route. I attempted to use rankby=distance in my Nearby Search request, but it didn't work because it requires a lo ...

What is the goal of JSON.parse(JSON.stringify(x))?

During my recent project work, I stumbled upon the following code snippet: let newParams = JSON.parse(JSON.stringify(initialParams)); I'm curious - what exactly does this code achieve? ...

What is the sequence in which middleware and callback functions are executed in Node.js?

I'm just starting out with node.js, and I have a file called app.js that references another file named xmlParser.js. The purpose of this is to parse an input xml file using the xml2js node module. Here's a snippet from app.js: //Require modules ...

Using React: implementing a spinner upon clicking a button and transitioning to a new screen when the animation finishes

I have noticed that there are existing answers on incorporating spinners during fetch requests completion. However, my query pertains to stopping the animation once it reaches completion after a timeout. Additionally, I am seeking advice on best practices ...

What is the best method for uploading a JSON file to a React web application and retrieving the file's link?

Is there a way to upload a JSON file to my React application and obtain the link to that file? Our app developer is working on implementing app linking and has requested this functionality. ...

Displaying a subset of categories based on the user's selection

I have been trying to find a solution to automatically display a subcategory select drop-down only when a user selects a category. If no category is selected, the subcategory drop-down should remain hidden. I have searched online tutorials and videos for ...

React Router version 6.4.5, automatic redirection upon loading the page

Seeking assistance with setting up redirects. Below are snippets of the code. index.js const router = createBrowserRouter([ { //Defining App as the root element... path: "/", loader: () => { }, element: <App/>, ...

JavaScript: Learn how to simultaneously open two links from the current webpage

I am trying to create a browser bookmark that will open a link with the id: window.getElementById('updateOk').click() followed by opening a small window with another button: document.getElementsByClassName('rmit-save-details btn btn-inlin ...

Maintaining Object Position in 2D Transforms

I am trying to create multiple perspective-transformed rectangles in the lower right corner of a canvas by using ctx.transform: ctx.transform(1, 0, -1, 1, 10, 10). My goal now is to adjust the size of the drawing based on a variable scale=n, while keeping ...

What is the process for obtaining a client-side cookie using next.js?

I'm currently facing an issue where I can't seem to maintain a constant value for the isAuthenticated variable between server-side and client-side in next.js. In my setup, I am using a custom app.js file to wrap the app with Apollo Provider. The ...

Troubleshooting server-side sorting issues with AJAX implementation, encountering problems with headers functionality

I'm encountering a problem: Some headers are not functioning properly to sort the table. For example, Brand and Model work as expected, but VehicleType only works once, and CarID and ReleaseDate never seem to work. Here is my index.php file: index. ...

What is the equivalent of $.fn in AngularJS when using angular.element()?

Currently, I am conducting a directive unit test using jasmine. The test is now functional, but I need to find an alternative for $.fn in angularjs since the use of $ is prohibited in my workplace. Code: (function scrollTopEventDirective(application) ...

Tips on adjusting the pixel dimensions of an image using a file object

Within a form on our website, users have the ability to upload an image file. To ensure quality control, I've set up validation to confirm that the uploaded file is either an image or gif format. In addition to this, I'm looking for a solution th ...

How can I apply various textures in three.js?

Hello there! I'm diving into the world of threejs and currently working on a block game similar to Minecraft. Instead of relying solely on objects, I've decided to build my program using planes (specifically the PlaneGeometry class). As I wrap ...

How can I use an HTML button to activate a function that inserts text into a read-only text-box?

Trying to write a simple piece of HTML code that finds the number greater than or equal to the first initial amount that wholly divides the second given amount. The code attempts to divide the numbers, and if it fails, increments the first number by 1 and ...

What is the best way to initiate a fresh AJAX request whenever the submit button is pressed?

Every time the submit button is clicked on my form, a modal appears and gets filled with JSON data from the application /addresschecker. If I receive an error message with a code return number of 2003, it indicates an issue with the addresses provided. Oth ...

Does jQuery mobile lack a back button feature?

Thoughts swirling in my mind: <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title></title> <script src="<?php echo base_url();?>/assets/js/vendor/modern ...

Ensure menu options are aligned to the right using material-ui

My material-ui menu currently has the following setup: <span> <Link to="/issues"> <Button style={isActive(history, "/issues")}>Issues </Button> </Link> <Link to="/users"> <Button style={isActive(his ...

Oops! Looks like there's a hiccup with the express-validator plugin as the validation fails due to req.checkBody not being recognized as

Currently, I am setting up a post route to handle a submit request. The code snippet provided is from my user.js route: var express = require('express'); var router = express.Router(); var multer = require('multer'); var upload = multe ...