JavaScript implementation cross-browser add and remove event binding function instances _javascript tips

Source: Internet
Author: User

The examples in this article describe the JavaScript implementation of Cross-browser Add and remove event binding functions. Share to everyone for your reference. Specifically as follows:

The event-binding function of IE is attachevent, while Firefox, Safari is Addeventlistener;opera, both are supported. Using jquery, you can use a simple bind (), or a function such as $ (). Click (), and if you don't use the JavaScript framework, you use the following encapsulated bind () function.

Add event bind bind ()

/************************************
* Add Event binding
* @param obj  : element
* @param type: Event name to bind the event. "On" is not added. such as: "Click" rather than "onclick.
" * @param fn  : event handler
************************************/function
bind (obj, type, fn) {
  if ( obj.attachevent) {
    obj[' e ' +type+fn]= fn;
    Obj[type+fn]=function () {
     obj[' e ' +type+fn] (window.event);
    }
    Obj.attachevent (' On ' +type, Obj[type+fn]);
  else
    Obj.addeventlistener (type, fn,false);


For example, add a click event to the document:

var fn=function () {
  alert ("Hello, world!!");
Bind (document, "click", FN);

Delete Event binding unbind ()

Unbind () for the bind () function above

/************************************
* Delete Event binding
* @param obj: the element
* @param type: event name to delete the event. "On" is not added. such as: "Click" instead of "onclick"
* @param fn: event handler
************************************/function
unbind (obj, Ty PE, FN) {
  if (obj.detachevent) {
    obj.detachevent (' on ' +type, Obj[type+fn]);
    Obj[type+fn]=null;
  } else
    Obj.removeeventlistener (type, fn,false);


For example, delete the first bound document Click event:

Copy Code code as follows:
Unbind (document, "click", FN);

I hope this article will help you with your JavaScript programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.