The HTML code is failing to detect the eventListeners

Does anyone know why my JavaScript event listener is not working when I try to link it to my HTML? They are in separate text documents, but I'm not sure if that's the issue. It seems to work with other sections, so there might be a small mistake that I haven't yet noticed.

<!DOCTYPE html>
<meta charset="utf-8">
<body>
<head>
<title>Outliner</title>
<link href="style.css" rel="stylesheet" title="Style">
<script type= "text/javascript" src='setting.js'></script>
<div>
  <input type="button" onclick="reset();" value="Reset form">
  <button id="pr" onclick="reset()"> Clear </button>
  <div id="ul" class="editor" contenteditable="true" draggable="true" ></div>
  </div>
</head>
</body>

const TAB_KEY = 9;
const ENTER_KEY = 13;

let editor = document.querySelector('.editor');

editor.appendChild(document.createElement('li')); // Add initial (for visibility)

window.editor.addEventListener('focus', (e) => {
  //let ul = e.target;
  //let li = document.createElement('li');
 //ul.appendChild(li);
});

window.editor.addEventListener('keydown', (e) => {
  let code = e.keyCode || e.which;
  if (code == TAB_KEY) {
    e.preventDefault(); 
    let parent = e.target;
    let ul = document.createElement('ul');
    let li = document.createElement('li');
    ul.appendChild(li);
    parent.appendChild(ul);
    moveCursorToEnd(li);
  } else if (code == ENTER_KEY) {
    e.preventDefault(); // Stop treating it like an actual line feed
    let parent = e.target;
    let li = document.createElement('li');
    parent.appendChild(li);
    moveCursorToEnd(li);
  }
});

function moveCursorToEnd(el) {

  el.focus();

  document.execCommand('selectAll', false, null);

  document.getSelection().collapseToEnd();
}

Answer №1

After troubleshooting, I discovered that the main issue was with window.editor, which was throwing an error

cannot use property addEventListener of undefined
. By simply replacing window.editor with editor, the problem was resolved.

To see the fix in action, try typing in the contenteditable div below using editor instead of window.editor. The scope of the variable was affected because it was declared with let instead of var, causing it not to be a property of the window object.

const TAB_KEY = 9;
const ENTER_KEY = 13;

let editor = document.querySelector('.editor');

editor.appendChild(document.createElement('li')); // Add initial (for visibility)

/*editor.addEventListener('focus', (e) => {
  //let ul = e.target;
  //let li = document.createElement('li');
 //ul.appendChild(li);
});*/

editor.addEventListener('keydown', (e) => {
  /*let code = e.keyCode || e.which;
  if (code == TAB_KEY) {
    e.preventDefault(); 
    let parent = e.target;
    let ul = document.createElement('ul');
    let li = document.createElement('li');
    ul.appendChild(li);
    parent.appendChild(ul);
    moveCursorToEnd(li);
    } else if (code == ENTER_KEY) {
    e.preventDefault(); // Stop treating it like an actual line feed
    let parent = e.target;
    let li = document.createElement('li');
    parent.appendChild(li);
    moveCursorToEnd(li);
  }*/
  alert("Works");
});
<div>
  <input type="button" onclick="reset();" value="Reset form">
  <button id="pr" onclick="reset()"> Clear </button>
  <div id="ul" class="editor" contenteditable="true" draggable="true" ></div>
</div>

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

a beginner's guide to utilizing the grunt target

Here is an example of my Gruntfile.js: 'use strict'; module.exports = function(grunt) { grunt.initConfig({ grunt.config.set('targ', grunt.option('target')); cachebuster: { build: { ...

Prevent the user from selecting an option if the value is already present

In the process of creating a library membership form, I am utilizing an ajax request to populate the student list in a select option. The goal now is to disable the options for students who are already members of the library. View of the Form <div cla ...

Struggling to access content with Protractor Promise callbacks. What is the best approach for invoking methods on the returned item?

Upon hitting the debugger in the code snippet below, the value of 'thing/item' shows as empty (refer to the image). it('CheckAllLinks:', function () { browser.ignoreSynchronization = true; browser .findElements(by.tagNa ...

Steps to develop a runnable Express API

After developing a basic yet fully functional Node.js Express API application using JavaScript, I am now looking to convert it into an executable file that can be run on Windows systems. The main reason behind this is to provide clients with the option of ...

hiding an "input type="file" element by using a button to conceal it

Is it possible to create a button that triggers file upload functionality? I couldn't find any solutions on Google. I've heard it can be done with labels, but I specifically need to use a button for better UX/UI. <button style="position:fixe ...

Folding into itself lies another folding

While attempting to nest a collapse area inside another collapse, I encountered an issue. Upon clicking to open the first collapse, it functions perfectly. However, when trying to open the second collapse (nested within the first one), it inadvertently cl ...

NodeJS API Language Configuration

I'm currently working on integrating the DuckDuckGo Instant Answer Api into my NodeJS application. To do so, I am making a data request from the API using Node Request. var request = require('request'); request('http://api.duckduckgo.c ...

Using SCSS to apply a class in Next.js

Currently, I am working on a project using Next.js and implementing the SCSS module procedure for styling. An example component directory structure is as follows: SampleComponent -> index.tsx and SampleComponent.module.scss The code in SampleComponent ...

Divide a string within a JSON object and output it as an array

I've encountered a challenge while working with data received from an API. My goal is to loop through this information and generate HTML elements based on it. The issue lies in the 'subjects' data, which arrives as a string but needs to be m ...

What are some strategies for navigating the constraint of having multiple root elements in Vue.js?

Seeking assistance from the experts here to solve this particular issue. I have a dataset that looks like this: [ { title: 'Header', children: [ { title: 'Paragraph', children: [], }, ], }, ...

Three.js experiencing issues with FBX animations running erratically

Having trouble with animations on some fbx models. When an animation lasts 20 seconds, the model remains stationary for 19 seconds and then suddenly moves within the last second or so. However, other fbx models animate correctly. The code used to run the a ...

Is it possible to jest at a module function that is both exported and utilized within the same module?

Just diving into unit testing and learning about spies, stubs, and mocks. I've been trying to test the verify method in password.js as shown in the code snippet below. However, I'm having trouble creating a stub for the hash function within the ...

Node.js: Breaking the Rules with an Illegal Break Statement

Struggling to generate a unique ID in Node.js and MongoDB, using a while loop that checks existing IDs in MongoDB until a unique value is found. If the ID is already taken, a number is added to the end until Mongo returns no results. Everything seems to b ...

Error message encountered while using Node.JS IPFS: TypeError occurs when attempting to send a message, as it cannot read undefined properties related to 'publish

Every time I attempt to send a message over the IPFS network, I encounter the following error message: TypeError: Cannot read properties of undefined (reading 'publish'). This error crops up at line number node.pubsub.publish(topic, msg, (err) = ...

Challenges with Pushing Arrays to JavaScript Class Prototype

Upon clicking a button, I have the following script that triggers: <button>Click</button> <script> var test = function(){}; test.prototype = { item:[] }; $(document).ready(function(){ $("button").on('click',fu ...

Techniques for simulating functions in Jest

I have a pair of basic components that I'm currently creating tests for using jest. My goal is to verify that when I click on a currencyItem, the corresponding array gets added to the select state. To achieve this, I am passing the handleCurrencyToggl ...

Tips for setting up Highcharts tooltip.headerFormat using the function getDate() plus 5

I'm facing a little challenge trying to understand how the JavaScript function getDate interacts with Highcharts datetime on xAxis. My goal is to show two dates in the tooltip header, forming a date range like this: 1960/1/1 - 1965/1/1. The first da ...

Is it possible to execute two separate functions within a single Node.js file using distinct command line prompts?

In my project, I have a .js file that imports an NPM package and contains two functions that utilize that package: //replacePaths.js import {replaceInFile} from 'replace-in-file'; async function replace() { const options = { files: &a ...

Express.js encounters a 404 error when router is used

I am currently in the process of learning and consider myself a beginner at Node.js. My goal is to create a basic REST API, but I keep encountering an error 404 when attempting to post data to a specific route using Postman to test if the information has b ...

Is it possible for Jquery to directly retrieve the form input without the need for a SET button in the script?

I have a script that functions as a basic countdown. All you need to do is enter a number, press the SET button, and click START for the countdown to begin. Although I primarily use this script in the gym, I often forget to hit the SET button after enteri ...