官术网_书友最值得收藏!

Working with browser events

When are you developing for browsers, you will have to deal with user interactions and events associated to them, for example, text typed in the textbox, scrolling of the page, mouse button press, and others. When the user does something on the page, an event takes place. Some events are not triggered by user interaction, for example, load event does not require a user input.

When you are dealing with mouse or keyboard events in the browser, you can't predict when and in which order these events will occur. You will have to constantly look for a key press or mouse move to happen. It's like running an endless background loop listening to some key or mouse event to happen. In traditional programming, this was known as polling. There were many variations of these where the waiting thread used to be optimized using queues; however, polling is still not a great idea in general.

Browsers provide a much better alternative to polling. Browsers provide you with programmatic means to react when an event occurs. These hooks are generally called listeners. You can register a listener that reacts to a particular event and executes an associated callback function when the event is triggered. Consider this example:

<script> 
  addEventListener("click", function() { 
    ... 
  }); 
</script>

The addEventListener function registers its second argument as a callback function. This callback is executed when the event specified in the first argument is triggered.

What we saw just now was a generic listener for the click event. Similarly, every DOM element has its own addEventListener method, which allows you to listen specifically on this element:

<button>Submit</button> 
<p>No handler here.</p> 
<script> 
  var button = document.getElementById("#Bigbutton");
  button.addEventListener("click", function() {
    console.log("Button clicked."); 
  }); 
</script>

In this example, we are using the reference to a specific element—a button with a Bigbutton ID—by calling getElementById(). On the reference of the button element, we are calling addEventListener() to assign a handler function for the click event. This is perfectly legitimate code that works fine in modern browsers such as Mozilla Firefox or Google Chrome. On Internet Explorer prior to IE9, however, this is not a valid code. This is because Microsoft implements its own custom attachEvent() method as opposed to the W3C standard addEventListener() prior to Internet Explorer 9. This is very unfortunate because you will have to write very bad hacks to handle browser-specific quirks.

主站蜘蛛池模板: 西乡县| 友谊县| 铜鼓县| 当阳市| 司法| 恩施市| 印江| 巫溪县| 华安县| 石屏县| 贵德县| 阜阳市| 遵义市| 中超| 禄劝| 崇明县| 芜湖县| 巫溪县| 达孜县| 保山市| 临江市| 乐清市| 蒲江县| 什邡市| 阿勒泰市| 崇礼县| 武义县| 固安县| 阿坝县| 庆元县| 孟村| 仁化县| 新巴尔虎左旗| 辽阳县| 斗六市| 长寿区| 通榆县| 陆川县| 柳河县| 兰考县| 文化|