Having trouble integrating document.getElementById('password').addEventListener() in a webpack and ES6 environment

I have a project where I am utilizing webpack and ES6 classes. In this particular scenario, I am attempting to trigger the 'onblur' function on input#password but unfortunately, it is not working as expected. Strangely, there are no errors thrown, and the callback function is also not being called. When I try to inspect the input#password element outside of the event listener using console.log(document.getElementById('password')), it correctly shows the input#password as a DOM object. I am lost and unsure of what mistake I might be making here. Below you can find the code snippets for reference:

index.html

    <head>
      <script src="./bundle.js"></script>
    </head>
    <body>
       <input id="password" type="password" placeholder="Please enter your password" autofocus="autofocus">
    </body>

webpack-config.js

const path = require('path');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
    },
    devServer: {
        contentBase: path.join(__dirname, 'dist')
    }
};

index.js

import { Password } from './app/main';

document.getElementById('password').addEventListener('onblur', () => {
    console.log('I'm stuck at this point');
    var initPwd = new Password();
    initPwd.init();
})

main.js

class Password {
    init() {
        console.log('I am inside init.')
    }
}

export { Password }

Your assistance would be greatly appreciated!

Answer №1

document.getElementById('password').addEventListener('onblur', () => {

=>

document.getElementById('password').addEventListener('blur', () => {

In this scenario, using onblur in element.onblur = function() {} would be the appropriate approach. When utilizing the addEventListener interface, omitting the on prefix in the event name is necessary.

Answer №2

The issue lies in the fact that the event name is set to blur, but you should assign handlers by setting the onblur property of the element. This difference between the two can cause confusion.

When adding a listener by assigning to a property, you need to use the syntax

<element>.on<eventName>
, for example:

element.onclick = () => ...
element.onblur = () => ...

On the other hand, when using addEventListener, you just specify the event name without the "on":

element.addEventListener('click', () => ...
element.addEventListener('blur', () => ...

Therefore, update it to:

document.getElementById('password').addEventListener('blur', () => {

document.getElementById('password').addEventListener('blur', () => {
  console.log('blur');
});
<input id="password" type="password" placeholder="Please enter your password" autofocus="autofocus">

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

Extract latitude and longitude data using Mapbox's autocomplete feature

Currently, I have integrated Mapbox with autocomplete in a Vue component: <template> <div> <div id='geocoder'></div> </div> </template> <script> import mapboxgl from 'mapbox-gl& ...

How to automatically disable a button in reactjs when the input field is blank

I have a component called Dynamic Form that includes input fields. The challenge I am facing is how to disable the submit button when these input fields are empty, although the validateResult function fails to return false. import cn from "classname ...

Is there a way for me to verify if I have already made an AJAX data request

I have an image gallery with thumbnails. When a user clicks on a thumbnail, an ajax request is fired. I want to prevent the ajax request from firing again if the user clicks on the same thumbnail and instead use the existing data. $.getJSON(url, function( ...

Typescript double-sided dictionary: a comprehensive guide

Looking for a dual-sided dictionary implementation in TypeScript that allows you to retrieve values using keys and vice versa. An initial approach could be storing both items as keys: dict = {"key": "value", "value": "key"} But I am curious if there are ...

Incorporating a YouTube channel into mobile websites

While it's relatively easy to embed single YouTube videos in mobile pages with the help of Google, I'm still struggling with embedding a whole channel. The issue seems to revolve around the screen width, and my attempts at using JavaScript have n ...

The <Button> element is incompatible with popups. (HTML, CSS, JS)

I've been struggling with this issue. I used CSS color values to create a smiley face, but when I added a button it messed up the design (adding an unwanted circle around the center of the smiley). I attempted to synchronize the button tag with the po ...

Why does the Element.style.left property keep rejecting my input value?

I have encountered a problem with the positioning of elements, specifically with the 'left' property. I've designed a rectangular block using CSS and rotated it by 0.17 radians in JavaScript. Now, my aim is to make the block move diagonally ...

Angular - Error: Cannot read property 'publishLast' of undefined

My goal is to prevent multiple requests from being created when using the async pipe. I am facing an issue with a request to fetch a user from the API: getUser() { this._user = this.http.get<User>(environment.baseAPIUrl + 'user') ...

Take away the attention from the span element

I have been experimenting with the following jsfiddle and attempted various methods suggested in this Stack Overflow thread, but I am struggling to remove the focus from the "feedback" span after clicking on the cancel button in jQuery confirm dialog. Her ...

How to make an AJAX request in jQuery / JavaScript after a specific time interval has passed

Here is the code snippet I'm working with: $('input.myinput').each(function(){ var id = $(this).val(); var myajax = function(){ $.ajax({ url: ajax_url, type: "GET", data: ({ code: id ...

What is the most efficient way to transfer an object between two functions in AngularJS?

As a beginner in AngularJS and Javascript, I recently attempted to pass an object from one function to another. Here is the HTML Code: <div ng-click="getValueFromHtml(userObj)">send Object </div> This is the Controller Code: $scope.getValueFr ...

In my React JS project, I am using an <Add /> component on two distinct pages. However, I am encountering an issue where only one of the pages is correctly receiving the add count prop

I could use some assistance in understanding why the logic for my counter button is not functioning properly on one specific instance. My aim is to have the count displayed by the counter look like this: https://i.sstatic.net/VdJ8o.png In order to add it ...

Check and uncheck checkboxes in a hierarchical structure in real-time

I am facing a similar question to a previously solved issue regarding unchecking parent nodes if all children are unchecked using JQuery, but I am attempting to enhance the solution by ensuring that the children will also all uncheck if the parent is unche ...

Error: The object "request" has not been defined. This issue occurs when trying to execute an Action

$dd = "<a href='javascript:void(0);' id='requestsend$send_id' onClick='request($send_id,request_send);' class='post-add-icon inline-items'><button type='button' style='background: #ccc;' ...

Troubleshooting the onExited callback issue with Popover component in Material UI

<Popover key={element.name} classes={{ paper: classes.paper }} open={open} anchorEl={this.myRef.current} anchorOrigin={{ vertical: ' ...

Merging elements of an array

There is a single array that holds appointmentID (first value) and supperBillID (second value) separated by a comma. The AppointmentID will always be unique, but the superBillID can be repeated in consecutive positions. The goal is to create an array that ...

There was no popcorn mix-up in your document

Encountering an issue while using grunt for staging (grunt serve): Running "bower-install:app" (bower-install) task popcornjs was not injected into your file. Please check the "app\bower_components\popcornjs" directory for the required file, an ...

Route Separation with ExpressJS and Socket.IO

As I delve into the world of ExpressJS and Socket.IO, I find myself facing a puzzling situation. My routes are neatly organized in a separate file that I include from my app.js: var express = require('express') , db = require('./db&ap ...

Encountering issues when attempting to parse file with webpack, react, and react-dom

I've been struggling with this issue for hours, trying various solutions without success. I've attempted different implementations, but none seem to work. ERROR message ERROR in ./app/main.js Module parse failed: /Users/DS/Code/tryouts/react-bo ...

Is it acceptable to use JavaScript files in the pages directory in NEXTJS13, or is it strongly advised to only use TypeScript files in the most recent version?

In the previous iterations of nextJS, there were JavaScript files in the app directory; however, in the most recent version, TypeScript files have taken their place. Is it still possible to begin development using JavaScript? I am working on creating an a ...