About the onchange event under IE and FF performance and solution

  • 2020-03-30 02:18:27
  • OfStack

On a recent project, there was a feature point where there was a checkbox on the page, and when the user selected or deselected the checkbox, a jsonp request was sent to the background. The implementation was to add an onchange event to the checkbox, but it turned out to be a surprise, so I took a closer look and found the following problems with the performance of the onchange event under IE and FF.

Question 1: Under FF, the onchange event is triggered immediately when you change the checkbox's checked state. However, when you change the checkbox's checked state under IE, the onchange event does not start immediately. Instead, it starts when the checbox loses focus.

To solve this problem, I added this.blur() to the onclick event of the checkbox. This is because the onclick event was executed before the onchange event, so adding this.blur() to the onclick event causes the checkbox to lose focus and immediately triggers the onchange event. But then there is the second problem.

Question (2) : When the onclick event is used with this.blur, an error is reported under IE.

After searching some materials on the Internet, I finally found the event onpropertychange. This event is not triggered under FF. Under IE, the checkbox starts immediately when the selection state changes. The final solution is to bind the onpropertychange event for the checkbox under IE and the onchange event for it under FF.

The specific code is as follows:


var ua=navigator.userAgent.toLowerCase();
var s=null;
var browser={  
  msie:(s=ua.match(/msies*([d.]+)/))?s[1]:false,  
  firefox:(s=ua.match(/firefox/([d.]+)/))?s[1]:false,  
  chrome:(s=ua.match(/chrome/([d.]+)/))?s[1]:false,  
  opera:(s=ua.match(/opera.([d.]+)/))?s[1]:false,  
  safari:(s=ua.match(/varsion/([d.]+).*safari/))?s[1]:false  
}; 
if(browser.msie){//If for Internet explorer browser
    checkbox.onpropertychange=function(){
         //do someting
    }
}
else{
    checkbox.onchange=function(){
        //do something
    }
}


Related articles: