Failing to trigger the event when connected via addEventListener

I'm currently working on developing a function to calculate the number of characters remaining. My aim is to utilize addEventListener to monitor event types:

var output = document.getElementById('output');
var tweetTxt = document.getElementById("tweettext");
var charCount = 10;
var tweetTxt = document.getElementById("tweettext");

 
function textCounter(){
console.log("it works");
var count = charCount - document.getElementById("tweettext").value.length;

if(count < 0){
output.classList.add("red");
output.classList.remove("black");
console.log("Less than zero");
}else{
output.classList.add("black");
output.classList.remove("red");
}
output.innerHTML = count + " characters left";
}


  tweetTxt.addEventListener('onKeyDown', textCounter, false);
  tweetTxt.addEventListener('onKeyUp', textCounter, false);
  tweetTxt.addEventListener('onChange', textCounter, false);
<div class="container">
<div class="row">
<div>
<textarea name="tweettext" id="tweettext">

</textarea>
</div>
<div id="output" class="black">

</div>
</div>
</div>

For some reason, this approach isn't producing the desired outcome. However, when I attach listeners directly to the <textarea> element, it functions properly:

  var output = document.getElementById('output');
//var tweetTxt = document.getElementById("tweettext");
var charCount = 10;
var tweetTxt = document.getElementById("tweettext");

 
function textCounter(){
console.log("it works");
var count = charCount - document.getElementById("tweettext").value.length;

if(count < 0){
output.classList.add("red");
output.classList.remove("black");
console.log("Less than zero");
}else{
output.classList.add("black");
output.classList.remove("red");
}
output.innerHTML = count + " characters left";
}


 /* tweetTxt.addEventListener('onKeyDown', textCounter, false);
  tweetTxt.addEventListener('onKeyUp', textCounter, false);
  tweetTxt.addEventListener('onChange', textCounter, false); */
<div class="container">
<div class="row">
<div>
<textarea name="tweettext" id="tweettext" onKeyUp="textCounter();" onKeyDown="textCounter();" onChange="textCounter();">

</textarea>
</div>
<div id="output" class="black">

</div>
</div>
</div>

Therefore, what am I overlooking in the initial implementation using addEventListener?

Answer №1

Instead of using the "on" prefix when attaching an event using addEventListener, it is recommended to use the event name directly. For example, use keydown instead of OnKeyDown.

 tweetTxt.addEventListener('keydown', textCounter, false);
 tweetTxt.addEventListener('keyup', textCounter, false);
 tweetTxt.addEventListener('change', textCounter, false);

DEMO

Note: Please note that the addEventListener() method is not supported in Internet Explorer 8 and earlier versions.

Answer №2

Simply update the event name in your code to:

var output = document.getElementById('output');
var charCount = 10;
var tweetTxt = document.getElementById("tweettext");

function textCounter(){
  console.log("it works");
  var count = charCount - document.getElementById("tweettext").value.length;

  if(count < 0){
    output.classList.add("red");
    output.classList.remove("black");
    console.log("Less than zero");
  }else{
    output.classList.add("black");
    output.classList.remove("red");
  }
  output.innerHTML = count + " characters left";
}

tweetTxt.addEventListener('keydown', textCounter, false);
tweetTxt.addEventListener('keyup', textCounter, false);
tweetTxt.addEventListener('change', textCounter, false);
<div class="container">
  <div class="row">
    <div>
      <textarea style="width: 100%" name="tweettext" id="tweettext" rows="10"></textarea>
    </div>
    <div id="output" class="black">

    </div>
  </div>
</div>

Keep in mind that attaching multiple events to one element can cause them to trigger multiple times. For instance, when typing, each character may fire 2 events (key down and key up), and when losing focus on the textarea, the change event will fire.

To avoid this issue, it's recommended to use either keyup or keydown events with additional conditions to ensure only valid characters are counted. If you don't need real-time updates, the change event is a suitable alternative.

Alternatively, you can also replace keyup and keydown with the input event:

tweetTxt.addEventListener('input', function(e){
  // your code here
});

Best of luck with your coding endeavors!

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

Issue with altering transparency using a JavaScript while loop

I'm attempting to create a blinking effect for an image by continuously fading it in and out. I've implemented two while loops to adjust the opacity attribute of the element - each loop changing the opacity by 10% and pausing for 10ms. Although t ...

Encountering an unspecified array type when making an Ajax request with JSON

Currently, I am developing a web application that allows users to play sudoku with a Java back-end. To communicate with my jQuery using Ajax, I have created a servlet. Upon sending the generated array (the sudoku) to my web application through this servle ...

Managing React state with custom objects

We are currently utilizing a react table component that requires selections to be maintained across different pages. To achieve this functionality, we have implemented a Map to store the selected rows and a custom class named Selections to manipulate these ...

What is the technique for extracting data from a Firebase application after a user has successfully logged in?

I'm currently facing an issue with my website's forum, which is integrated with Firebase for storing forum posts and user login information. The challenge I'm encountering involves retrieving data from the logged-in user's child in orde ...

What is the best way to use an object as a key to filter an array of objects in JavaScript?

My data consists of an array of objects: let allData = [ {title:"Adams",age:24,gender:"male"}, {title:"Baker",age:24,gender:"female"}, {title:"Clark",age:23,gender:"male"}, {title:"Da ...

Server-side script for communicating with client-side JavaScript applications

Currently utilizing a JavaScript library that uses a JSON file to display content on the screen in an interactive manner. (::Using D3JS Library) While working with clients, it is easy to delete, edit, and create nodes which are then updated in the JSON fi ...

Forcing UTF-8 Encoding in JavaScript

I came across this helpful article: While following the advice of many others suggesting to use unescape(encodeURIComponent(srt)), I encountered issues. Attempting to convert the file obtained through XMLHttpRequest did not yield the desired results. Pri ...

Place the simulation nodes in designated locations

Is there a proper way to position nodes at specific coordinates using simulation force in D3.js? I am trying to place nodes at specific positions with forceX/Y simulation in D3.js. My understanding is that setting the strength to 0 should result in no for ...

In right-to-left mode, two items in Owl Carousel vanish while dragging or touching

When using owl carousel 2 with the RTL option, I encountered an issue where the carousel disappears when dragging/touching the last item (5 or 6 slides to the right, it disappears). I prefer not to use the loop option to workaround this. How can I resolve ...

Turn off horizontal scrolling on your mobile site

I am working on a mobile webpage with a Facebook-like side menu button, but I'm having trouble disabling horizontal scrolling using CSS overflow-x:hidden. Here is the code I have so far: <meta name="viewport" content="width=device-width, initial-s ...

The proper way to link various asynchronous operations enclosed in promises

My current understanding of promises is that they serve as a wrapper for async functions within the outer environment (such as the browser or node.js). However, I am struggling with how to properly connect async operations using promises in software develo ...

Proceed to the next request after the initial request has finished executing in node

Imagine there is an endpoint called /print. Each time a request is sent to this endpoint, it triggers the function printSomething(). If another user hits this endpoint while printSomething() is still processing, it will run the function again simultaneousl ...

Introducing additional choices to the list and automatically refreshing the list with the latest updates

I am currently honing my skills in Yii2 by working on a project using this framework. One of the challenges I am facing is adding new list options dynamically without having to navigate away from the current page. When I click the "Add new option" button ...

Warning: The use of 'node --inspect --debug-brk' is outdated and no longer recommended

Encountering this error for the first time, please forgive any oversight on my part. The complete error message I am receiving when running my code is: (node:10812) [DEP0062] DeprecationWarning: `node --inspect --debug-brk` is deprecated. Please use `node ...

Should I utilize Sockets or Ajax for my project?

My Login Script Journey I have a goal in mind - to create a login script using Nodejs. I am currently exploring the options of utilizing sockets or ajax posts for this task. My Progress So Far I have Nodejs installed and have referenced this code in my ...

Tips for triggering the .click() function upon returning to index.html after visiting a different page

I'm in the process of creating a portfolio website where the index.html page features a sliding navigation bar that displays a collection of projects. Each project is linked to a separate work.html page. I would like the sliding nav to automatically o ...

Running zgrep using node.js

I'm looking to incorporate the zgrep command into my node.js app. Currently, I have successfully integrated the grep command as shown below: const grep = require('grep1'); grep(['greptext', './logs/file], function(err, stdou ...

Retrieve JSON data using Google Chrome

I am encountering difficulties in fetching data from a local json file on my machine. Despite trying various solutions I found, I have been unsuccessful... Here is the code snippet I have used: When attempting to fetch the API, I encountered the error me ...

React component not consistently returning correct results due to undefined values being included

Currently, I have a function that iterates through one array, comparing its values with those in another array. When it finds a match, it adds the matching results to a new array called addToState. These matches are then concatenated with the original arra ...

JavaScript code failed to run

I am currently attempting to invoke a JavaScript script to export a chart from the PrimeFaces chart component. The issue I am facing is that the base64str variable appears to be null, and the script responsible for populating this value is not being called ...