Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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