Skip to content

Instantly share code, notes, and snippets.

@inter-coder
Last active December 17, 2019 17:03
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save inter-coder/d674758f727fa866f9e9 to your computer and use it in GitHub Desktop.
Save inter-coder/d674758f727fa866f9e9 to your computer and use it in GitHub Desktop.
changeValueDetection - Observer
HTMLElement.prototype.changeValueDetection = function(){
var element=this;
var oldVal=element.value;
var GUID = function (){var S4 = function () {return(Math.floor(Math.random() * 0x10000).toString(16));};return (S4() + S4() + "-" +S4() + "-" +S4() + "-" +S4() + "-" +S4() + S4() + S4());};
var uiq="GUID-"+GUID();
if(window.changeValueDetectionEvents==undefined)window.changeValueDetectionEvents=new Event('changeValueDetection');
element.setAttribute("data-uiq",uiq);
window[uiq]=setInterval(function(){
if(element.value!=oldVal){
oldVal=element.value;element.setAttribute("value",oldVal);
element.dispatchEvent(window.changeValueDetectionEvents);
}
if(document.querySelectorAll("[data-uiq='"+uiq+"']").length==0){//clear interval, if element no exist
clearInterval(window[uiq]);
};
},100);
};
//example
document.getElementById("test").changeValueDetection();//init observer
document.getElementById("test").addEventListener("changeValueDetection", function(){
alert("element have new value: "+this.value);
});
//it will triger event even you change value with
document.getElementById("test").value="some new value";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment