Troubleshooting problem with the oninput function of a custom JavaScript element

Assume I have a unique requirement to trigger a function within a custom element. The goal is to update text in the element only when a slider is moved within that specific element. Here's an example implementation in the main.js file:


class OninputClassDemo extends HTMLElement {
    constructor(){
        super();

        const shadow = this.attachShadow({mode:'open'});

        this.parent = document.createElement('div');

        this.slider = document.createElement('input');
        this.slider.setAttribute('type','range');
        this.slider.setAttribute('min','0');
        this.slider.setAttribute('max','99');
        this.slider.setAttribute('value','0')

        this.text = document.createElement('input');
        this.text.setAttribute('type','text');
        this.text.setAttribute('value','');

        this.parent.appendChild(this.slider);
        this.parent.appendChild(this.text);
        shadow.appendChild(this.parent);        

        this.slider.oninput = () => {
            this.text.value = this.slider.value;
        }
    }
}

window.customElements.define('demo-element',OninputClassDemo);

In the HTML template:

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="main.js"></script>
</head>
<body>
    <demo-element></demo-element>
</body>
</html>

A common error might be:

OninputClassDemo.changeValue is not a function
    at HTMLInputElement.oninput

To address this, consider updating the event listener for the slider input like so:

this.slider.oninput = WhatShouldIPutHere;
. This way, you can ensure that the text box associated with only that specific object is updated dynamically.

Answer №1

To ensure proper event handling, it is recommended to bind event listeners using addEventListener instead of directly through the class name. Additionally, when setting values, it is best practice to utilize the value property rather than setting attributes.

class CustomInputDemo extends HTMLElement {
  constructor() {
    super();

    const shadow = this.attachShadow({
      mode: 'open'
    });

    this.container = document.createElement('div');

    this.slider = document.createElement('input');
    this.slider.setAttribute('type', 'range');
    this.slider.setAttribute('min', '0');
    this.slider.setAttribute('max', '99');
    this.slider.setAttribute('value', '0')

    this.text = document.createElement('input');
    this.text.setAttribute('type', 'text');
    this.text.setAttribute('value', '');

    this.container.appendChild(this.slider);
    this.container.appendChild(this.text);
    shadow.appendChild(this.container);

    this.slider.addEventListener('input', (event) => this.updateTextValue());

  }

  updateTextValue() {
    this.text.value = this.slider.value;
  }
}

window.customElements.define('input-demo', CustomInputDemo);
<input-demo></input-demo>

Answer №2

It is recommended to use the following code snippet:

updateValue() {
    this.text.setAttribute('value',this.slider.getAttribute('value'));
}

as opposed to:

updateValue = function(){
    this.text.setAttribute('value',this.slider.getAttribute('value'));
}

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

Having trouble retrieving coordinates from AJAX request to Google Maps API?

I am currently developing a weather application and one of the initial steps is to retrieve the longitude and latitude coordinates for a specific city based on its name. To achieve this, I am utilizing Google Maps API to gather the necessary information. ...

Is it possible for an ul to be displayed beneath a white section within an li

I am working on a JQuery carousel that is displaying correctly, but I want to make a small adjustment to the content: <li class="jcarousel-item jcarousel-item-horizontal jcarousel-item-1 jcarousel-item-1-horizontal" style="float: left; list-style: none ...

What is the best way to add HTML tags both before and after a specified keyword within a string using JavaScript?

Imagine I have a string similar to this, and my goal is to add html tags before and after a specific keyword within the string. let name = "George William"; let keyword = "geo"; Once the html tags have been appended, the desired result should look like ...

Enhance a React component by including additional properties when passing it into another component through props

I have a parent element with a dynamically changing height that I need to pass down to its child elements. To get and set the height of the parent element, I am utilizing a ref. The challenge lies in passing this height value from the parent component to ...

Issue with pre-selected checkboxes: JavaScript

A function was created to automatically check the first value of a checkbox when a page is loaded: function defaultCheck(){ document.checkBoxForm.list[0].checked = true; var val=document.checkBoxForm.list[0].value; showtotal[0] = docum ...

To view the following set of three images, simply click on the "load more" button

I'm looking to add a load more button to reveal additional images. Currently, the page loads with 3 images visible, and upon clicking the load more button, the next set of 3 images should be displayed on the screen. Unfortunately, the code I've ...

Guide on detecting and capturing a change in location history event

My main goal is to capture router change events outside of the NextJS framework, not within it. The application I have developed using NextJS includes some code that operates independently of the NextJS context. This code needs to be able to detect navigat ...

The onClick function is called when I fail to click the button within a React form

I set up a form and I would like to have 2 ways to submit it: One by filling out the input field and pressing enter One by recording voice (using the react-speech-recognition library) However, after adding the second way, the input fi ...

PHP may not be the only language that deals with website security concerns. This question on website security extends beyond just PHP and

Let's imagine we have files named "index.htm" and "routines.php". In the scenario, "index.htm" will eventually reach out to "routines.php" using JavaScript (AJAX). Now, here is the query: how can "routines.php" confirm that the request originated fr ...

Display issue with React TypeScript select field

I am working with a useState hook that contains an array of strings representing currency symbols such as "USD", "EUR", etc. const [symbols, setSymbols] = useState<string[]>() My goal is to display these currency symbols in a select field. Currently ...

Observables waiting inside one another

I've encountered an issue where I need to return an observable and at times, within that observable, I require a value from another observable. To simplify my problem, let's consider the following code snippet: public dummyStream(): Observabl ...

Step-by-step guide to launching a new window or tab without automatically bringing it into focus

Is it possible to use JavaScript to open a URL in a new tab without giving that tab focus on a click event? ...

How to use jQuery to retrieve the style of an element based on a specific data attribute

I've been using bxSlider and I decided to create a unique custom pager using the pagerCustom option. My goal was to make the pager resemble a thumbnail pager, so I attempted to copy the style of each slide and attach it to the corresponding pager. For ...

Component loader with dynamic rendering for multiple components

Currently, I am in search of a method to dynamically render components within my Angular application. While exploring various options, I came across the concept of dynamic component loading in Angular (refer to https://angular.io/guide/dynamic-component-lo ...

Updating a React application that was originally built using Node v16 to the latest version of Node, v18,

I have a React project that was originally built on node v16 and now I need to update it to node v18. How can I do this quickly without changing dependencies or causing other issues? When I tried installing the dependencies in node 18, everything seemed f ...

Discovering the worth of specific selections in a dropdown menu

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <select name="states" id="states"> <option value="100">Hawaii</option> <option value="107">Texa ...

Accessing variables from child controllers with populated select inputs in Angular

I'm currently facing an issue involving 3 controllers: Parent Controller: DocumentController Child Controller1: XdataController Child Controller2: CompanyController The child controllers are used to populate data in three Selector inputs on the fron ...

Having trouble hiding the hamburger menu depending on the screen width

I'm trying to figure out how to hide the hamburger menu when the screen width exceeds 400px. You can check out the site at damf.co Currently, the hamburger menu appears when the screen width is less than 400px. If you click on it and then expand the ...

Storing values in localStorage with a specific format can be accomplished by following these steps

How can I save a localStorage value with special characters? I currently have the following value: ald:20221219_1833|atrv:lMh2Xiq9xN0-is9qy6DHBSpBL3ylttQQew but when I try to store it, it appears as if there is an arrow indicating that the value can be ex ...

What could be the reason for Angular to merge the element at index 0 of an array into a subarray instead of doing

After setting up the Array in my oninit function, I encountered an issue where one part of the array was functioning as intended while the other returned an error. this.tests = [{ status: 0, testresults: [{ name: 'test ...