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

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.

主站蜘蛛池模板: 岱山县| 社会| 富民县| 弥渡县| 商城县| 隆昌县| 龙泉市| 大竹县| 阳江市| 台北县| 武鸣县| 乐清市| 孝昌县| 康保县| 同德县| 贞丰县| 铅山县| 东城区| 芮城县| 承德县| 寻乌县| 营口市| 壤塘县| 台东市| 龙陵县| 大埔县| 广宗县| 奈曼旗| 达日县| 洪洞县| 大名县| 孟连| 甘南县| 陇西县| 南安市| 嘉义市| 怀来县| 饶阳县| 丰县| 通海县| 南昌市|