Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if onpropertychange is supported or not?

I'd like to know if an input element has changed, I learned that I can listen to onpropertychange in IE and oninput in other browsers.
Here is my code:

var _addChangedProperty = function(input){
    input.changed = false;
    var oninput = function(){
        this.changed = !!this.value;
        if(this.changed){
            this.style.color = "black";
        }   
    };  
    input.onpropertychange = input.oninput = oninput;
};  

Now I'd like to change input.onpropertychange = input.oninput = oninput; to addEventListerner and attachEvent, I need to check if onpropertychange event is supported, how could I do this(without browser detect)?

like image 385
wong2 Avatar asked Oct 10 '22 20:10

wong2


1 Answers

You can check using the in operator:

"onpropertychange" in input

This kind of feature test doesn't work in older versions of Firefox, which report false event for event handler properties corresponding to events that do exist, but that isn't a problem here because Firefox doesn't currently support the propertychange event and is unlikely to in the future.

Here's some background: http://perfectionkills.com/detecting-event-support-without-browser-sniffing/

One other point: you need separate functions to handle the propertychange and input events, because in the propertychange handler you need to check whether it is the value property that has changed. Otherwise, you'll end up handling changes to any property of the input.

input.onpropertychange = function(evt) {
    evt = evt || window.event;
    if (evt.propertyName == "value") {
        // Do stuff here
    }
};
like image 185
Tim Down Avatar answered Oct 12 '22 10:10

Tim Down