Bind and block default events

Source: Internet
Author: User

Generally, we use return false to prevent default events. However, if you use event binding, return false will expire when browsing in a later version, but it is still possible in a lower version browser, we can use the preventDefault () method in the event object to solve the problem that events in the browser of a later version cannot be bound with return false to prevent default events.

For example, the default menu that appears after right-clicking is canceled

Document. oncontextmenu = function ()

{

Return false;

}

In this way, the default menu will not appear after you right-click each browser, but what if you use event binding:

Event binding function:

// Obj: add an event to the element

// SEv: event name

// Fn: execution function

Function addEvent (obj, sEv, fn)

{

If (obj. addEventListener) // indicates a browser of higher version.

{

Obj. addEventListener (sEv, fn, false );

}

Else

{

Obj. attachEvent ('on' + sEv, fn) // view earlier versions

}

}

Now we bind a right-click event to the document.

AddEvent (document, 'textmenu ', function (){

Return false;

})

At this time, you will find that, in the High Version browser, right-click, the menu can still appear, and in the lower version, right-click, the menu will not appear.

Solution:

AddEvent (document, 'textmenu ', function (ev ){

Var oEvent = ev | event;

OEvent. preventDefault & oEvent. preventDefault (); // This method is not supported by browsers of higher versions.

Return false;

})

In this way, the default method of the browser can be blocked after the binding event is solved perfectly, and the browser is compatible with various browsers.

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.