Watch for property of DOMNode

I am searching for a method to detect changes in a property of an object (specifically of type DOMNode).

The scenario involves an INPUT element, and I need to be able to track any modifications made to the .value property. The challenge lies in the fact that there is no attr definition available for this purpose. Even with MutationObserver not being suitable as it doesn't trigger on property definitions (input.value).

I am open to utilizing the latest features as compatibility with IE is not a concern.

Edit #1

To demonstrate my point, I have created this test:

  1. Manual triggering works but is not a viable solution;
  2. Automatic triggering is ineffective, which is preferable;
  3. __defineSetter__ performs well, but halts "default propagation".

If there is a way to allow __defineSetter__ to continue until the end, the issue would be resolved.

Answer №1

Are you looking to track user changes or programmatic changes in the input element? For modern browsers, monitoring the input event can inform you when the input field value is modified by user action. Unfortunately, there isn't a consistent way across different browsers to detect if the field value has been changed programmatically without implementing your notification system.

A while back, I crafted a cross-browser function to monitor all types of user modifications to an input field in various browsers. While this code snippet is written as a jQuery method, it can be adapted to plain JavaScript with ease. It examines whether the new events are supported and utilizes them if available. If unsupported, it attaches numerous events to capture all potential methods through which a user could alter the field (such as drag-and-drop, copy/paste, typing, etc.).

(function($) {

    var isIE = false;
    /*@cc_on
    isIE = true;
    @*/

    var events = [
        "keyup", false,
        "blur", false,
        "focus", false,
        "drop", true,
        "change", false,
        "input", false,
        "textInput", false,
        "paste", true,
        "cut", true,
        "copy", true,
        "contextmenu", true
    ];

    if (!isIE) {
        var el = document.createElement("input");
        var gotInput = ("oninput" in el);
        if  (!gotInput) {
            el.setAttribute("oninput", 'return;');
            gotInput = typeof el["oninput"] == 'function';
        }
        el = null;
        
        if (gotInput) {
            events = [
                "input", false,
                "textInput", false
            ];
        }
    }

    $.fn.userChange = function(fn, data) {
        function checkNotify(e, delay) {
            var self = this;
            var this$ = $(this);

            if (this.value !== this$.data("priorValue")) {
                this$.data("priorValue", this.value);
                fn.call(this, e, data);
            } else if (delay) {
                var eCopy = $.extend({}, e);
                setTimeout(function() {checkNotify.call(self, eCopy, false)}, 1);
            }
        }

        this.each(function() {
            var this$ = $(this).data("priorValue", this.value);
            for (var i = 0; i < events.length; i+=2) {
                (function(i) {
                    this$.on(events[i], function(e) {
                        checkNotify.call(this, e, events[i+1]);
                    });
                })(i);
            }
        });
    }
})(jQuery);    

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

Using the model's value as the name for another model in AngularJS

var app = angular.module('LoginApp',[]); app.controller('dynamicController', ['$scope', function($scope) { $scope.role= "Admin"; $scope.auctionNumber = 1; $scope.itemsArray = [{ letter:"a" , number:1 }]; }]); To d ...

Steps for deploying a monorepo using turborepo on Digital Ocean

I am working with a monorepo managed by turborepo. It consists of two packages - 'client' and 'api', located inside packages/* in the root folder. My current challenge is deploying the 'api' package to Digital Ocean, but I&apo ...

Modification of file types (HTML input[type=file])

Is it feasible to generate a new file of a specific type from the currently uploaded file in the input? After uploading a file, I attempted to modify its type directly within an onChange event but received an error stating that it is a read-only property ...

Immediately refresh the page after successfully loading the DOM through JavaScript

function selectDate(){ var d=document.getElementById("selecter").value; alert(d); var days=['Monday','Tuesday', 'Wednesday','Thursday', 'Friday', 'Saturday', 'Sunday']; / ...

Creating interactive table rows with expandable content in Vue.js using Element-UI

I have implemented a table with expandable row functionality. Currently, when the expand icon is clicked, the row expands. You can view an example HERE. However, I would like to make the entire row clickable in order to toggle between expand and collapse, ...

What is the method for activating a button when a user inputs the correct email address or a 10-digit mobile number

How can I enable a button when the user enters a correct email or a 10-digit mobile number? Here is my code: https://stackblitz.com/edit/angular-p5knn6?file=src%2Findex.html <div class="login_div"> <form action=""> <input type="text" ...

Validating clients with Bootstrap 4 before submitting via ajax

My project follows the guidelines of Bootstrap 4, so I aim to reuse existing code whenever possible instead of writing my own. I have a form (shown below) that triggers an AJAX post request upon pressing the Submit button. The response is a JSON object con ...

Using ReactJS to fetch data from a localhost PHP page

Currently, I am delving into the world of PHP and its integration with ReactJS. A peculiar issue has crossed my path, one that puzzles me as a solution seems out of reach. Displayed below is a simple form: class App extends React.Component { state ...

Stop users from being able to input line breaks by pasting

I am currently facing a challenge with my code. Within the code, I have included a textarea where users can input the title of an article, and I want this title to be restricted to only one line. To achieve this, I created a script that prevents users from ...

Retrieving specific items based on property and narrowing down a collection of objects using Mongoose

I'm currently developing a search feature that allows users to input a specific query and retrieve all messages containing that query. The search process involves sending a query to the database based on the current message context when the user init ...

Exploring the scope of event listeners in jQuery's TimeCircles

Currently experimenting with the jquery timer known as "TimeCircles", which can be found here. I have successfully set up a minute / second timer for 30 minutes with an alert that triggers at 25 minutes. My goal is to implement an event when the timer hits ...

Make sure to include the onBlur and sx props when passing them through the slotsProp of the MUI DatePicker

This DatePicker component is using MUI DatePicker v6. /* eslint-disable no-unused-vars */ // @ts-nocheck import * as React from 'react'; import { Controller } from 'react-hook-form'; import TextField from '@mui/material/TextField&a ...

Troubleshooting textarea resize events in Angular 6

In the development of my Angular 6 application, I have encountered an issue with a textarea element. When an error occurs, an asterisk should be displayed next to the textarea in the top-right corner. However, there is a gap between the textarea and the as ...

I used AJAX to fetch a file using jQuery, but I'm not sure where it gets saved to on my computer

$.ajax({ type: "GET", url: "http://example.com/file.txt", success: function(data){ alert( "File Downloaded Successfully: " + data ); } }); Can you please provide the download link for the file? Thank you! ...

Click on each item within the v-for loop to gather relevant information, and subsequently iterate through the collected data

Within a v-for loop, I have implemented a button that, when clicked, retrieves specific data. The objective is to display this data below or in place of the clicked button. <div v-for="(item, index) in items" :key="index"> <button @click="fetch ...

Ways to eliminate numerous swipe features in JavaScript on a webpage

Struggling to handle multiple swipers on the page, encountering an issue where the array is always empty in the destroy function for desktop width. The initialization process for mobile devices seems to be working fine. Have tried various methods but end u ...

Retrieve the id within the parentheses for each checkbox that is checked and re-check each time a checkbox is selected using Kendo UI

Working with the tricky kendo-ui has made adding selectors quite challenging; however, my current task involves simply obtaining the inner contents of the id selector upon clicking an input checkbox element. Specifically, I need to extract the text between ...

Navigating the browser view across an extensive HTML page without relying on scrollbars

I have a large HTML page (approximately 7000x5000) and I need to be able to move the user's view around with JavaScript. Disabling the ability for the user to scroll by hiding the browser scrollbars using overflow:hidden on the HTML element is easy. ...

Encountering a problem while trying to scrape using cheeriojs

While attempting to scrape article links from a website, I encountered an issue where only one link was successfully scraped and the other elements were not being looped over. My current setup involves using nodejs in conjunction with the cheerio and req ...

Using React Hooks to update the array state replaces the elements rather than appending them

Recently, I came across this interesting hook: const [pastChat, setPastChat] = useState([]); I've been utilizing it in a function that triggers when the user clicks on a button: const nextAction = (step) => { //...perform various tasks... ...