Extending a Native HTML Element: A Beginner's Guide to Customizing CustomElementsV0

My goal is to create a customized HTML element by extending HTMLInputElement and defining its default behavior for events like focus, change, click, keypress, etc.

After facing difficulties with CustomElementV1 due to an "Illegal constructor" error, I decided to explore the CustomElementV0 approach:

var Xinput = Object.create(HTMLInputElement.prototype);
Xinput.createdCallback = ()=>{
  this.addEventListener('change',(e)=>{
    console.info("field changed", e.target);
  });
};
var Xi = document.registerElement('x-input', { prototype: Xinput, extends: 'input'});

The actual node creation happens later:

var n = new Xi();

Upon running this code, I discovered that the this variable in the createdCallback function does not refer to the DOM node created with "new Xi()". Instead, it points to the Window object. As a result, the change event gets registered multiple times, triggering once for each x-input element present in the DOM. This issue was observed while using Chrome version 54 to 57.

I am now seeking guidance on the correct approach to ensure the event fires only once as expected. Any insights would be greatly appreciated.

Answer №1

According to the reference provided in the comment, it is advised not to utilize an arrow function for defining the createdCallback method as it will not alter the value of this.

Instead, opt for the conventional function() syntax:

Xinput.createdCallback = function () {
  this.addEventListener('change',e=>
    console.info("field changed", e.target)
  );
};

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

Upgrade your AngularJS Directive to an Angular 2.x+ Directive by using an HTML decorator

Is it no longer possible to utilize Angular directives as what I like to refer to as "HTML decorators"? I found this method extremely useful in Angular 1.x when transitioning legacy applications to Single Page Apps by creating a set of directives to enhan ...

Instructions on executing the command 'free -m' every minute and integrating it into the existing page (PHP exclusive)

I am looking to automate the process of running 'free -m' every minute and appending the result to the previous results. Goal: Run 'free -m' command every minute Action: Add the result to the existing data The script will only execut ...

Discovering the absent number within a cyclical array

Looking to find the missing number between two arrays in a cyclical manner using either Javascript or jQuery. It's easy to find all missing numbers, but I specifically need to identify the single missing number within the range of the second array whi ...

Submitting a form from a local HTML file to an external URL using Ajax

I'm facing a bit of a dilemma with my project. I have a local HTML file that contains some Forms. All the stylesheets and JavaScript files are hosted on a web server. The issue arises when I try to submit the forms using AJAX while opening the HTML ...

Creating an Efficient Lazy Loading HTML Page with jQuery

I've been looking to create a page that loads content only as the user scrolls to that specific section, similar to the way Pinterest website functions. Does anyone have suggestions on how to design and implement this feature, or know of any plugins ...

The file reader feature is currently experiencing issues on both Chrome and Internet Explorer browsers

After uploading an image file from my PC, I convert it to a data URL and then use the img element to preview it. Surprisingly, this process works perfectly fine in Firefox. However, when I try to do the same in Chrome or IE, the src attribute of the img el ...

Save Scope in JSON format

Currently, I am developing a web application that dynamically displays specific prompts based on the field in focus. There are several different texts stored as scripts that I want to showcase at these different points. My goal is to incorporate scope dat ...

What is the best way to randomly display an image from a JavaScript array within an HTML document?

I currently have this code in my HTML and JavaScript files, but I am having trouble with displaying images without using a URL in the JavaScript file. The images are located in my project folder. However, when I open the HTML file, the images do not appear ...

Tips for adjusting the color of multi-line text when hovering with the mouse

I'm facing a challenge in changing the color of text when someone hovers over it, but so far I've only been able to make it work if the mouse scrolls over the top border of the text. The text I'm testing is located in the top left corner an ...

Ways to avoid the browser from storing a JSON file in its cache

Hey there, I'm working on a project and running into some issues with caching. The problem I'm facing is that the browser keeps holding onto the json file containing save data even after I update it elsewhere. This means that the browser is readi ...

Ways to automatically include a local variable in all functions

In each of my functions, I start with this specific line: var local = {} By doing so, it allows me to organize my variables using the following structure: local.x = 1 local.y = 2 Is there a way to modify all function prototypes to automatically include ...

Creating the data type for the input file's state: React with Typescript

Encountering an error when attempting to define the type of a file object within state: Argument of type 'null' is not assignable to parameter of type 'File | (()=> File)'.ts. Currently working on an upload component that allows for ...

Troubleshooting Tips: Investigating a Service Call in AngularJS 2 using ES6 Syntax

MY DILEMMA: I have recently started learning Angular2 and found myself wanting to debug a service call. The service appears to have been properly called, as evidenced by the view display. However, when trying to log the content of the variable holding t ...

Can an internal/private function call a public function?

Just wondering if I'm missing something here, as I tried the following: (function() { var thing = function() { var doIt = function() { console.log("just do it"); this.updateValue(5); }; return { ...

Passing a dynamic data value to a click event in Google Analytics

I need help finding a solution for this issue. My goal is to track an event in Google Analytics through an onclick event, but I am struggling with passing a dynamic variable to the URL field. Below is the code snippet: <asp:hyperlink ID="Hyperlink2" r ...

How come my jQuery ajax request is successful but the $_POST array remains empty?

Here is my first query on this forum, please be patient with me: The code snippet for my ajax request is: <script> $.ajax({ type:"POST", url:"http://localhost/folder/something.php", data: { BuildingName:'Jacaranda'}, success: function(da ...

"Need to refresh localStorage in VueJS after navigating back with this.$router.go(-1)? Here's how

Below is my Login.vue code: mounted() { if (localStorage.login) this.$router.go(-1); }, methods: { axios.post(ApiUrl + "/login") { ... } then(response => { ... localStorage.login = true; this.$router.go(0); ...

Tips on retrieving PHP variable values along with HTML response using AJAX in PHP

I am looking to retrieve 2 variables: 1) The total number of records from the mysqli query performed in search_members.php 2) A boolean value indicating whether any results were found Below is the code I have written: <input type="button" value="Sea ...

What is the process for including a new item in a JavaScript dictionary?

I'm currently learning JavaScript and I've encountered a challenge. I have a dictionary that I'd like to update whenever a button is clicked and the user enters some data in a prompt. However, for some reason, I am unable to successfully upd ...

Multer can handle the uploading of various files from multiple inputs within a single form

I've searched everywhere on the internet, but I can't seem to find a solution that matches my specific issue. As someone new to Node.JS, I'm attempting to upload two different pictures using Multer from the same form. Here's what my for ...