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

Adding multiple event listeners to an HTML element

Listeners make an HTML element stand at the ready, waiting to do what it has been tasked with.

Getting ready

Once familiar with the built-in JavaScript and additional MooTool events that we can bind actions to, we note the addEvent() syntax from the previous recipe and move on to the more agile addEvents() syntax.

How to do it...

The syntax for adding multiple events is similar enough to adding a single event that one could nearly guess it. Look at this example to see how intuitive it is:

<script type="text/javascript" src="mootools-1.3.0.js"></script>
</head>
<body>
<div id="my_trigger" style="width:100px; height:100px; border:1px solid #BEBEBE; line-height:100px; text-align:center;"></div>
<script type="text/javascript">
$('my_trigger').addEvents({
'mouseover': function() {
this.set('html','MouseOver!');
},
'mouseout': function() {
this.set('html','MouseOut!');
},
'click': function() {
var width = (this.getStyle('border-width'). toInt()==1) ? '5px' : '1px';
this.setStyle('border-width',width);
}
});
</script>

How it works...

The syntax for adding multiple events is very similar to that of adding a single event. Remembering that addEvent() takes the event name and the function to execute, we can easily see that addEvents() takes the same two arguments, only in hashed form so that multiple event names can have individual functions applied to them.

There's more...

In our example, we have defined three events to listen for: onmouseover, onmouseout, and onclick. Remove the "on" prefix for events when using these functions.

Note

MooTools adds two important events that help to solve the event bubbling dilemma where each parent and children both report events causing them to fire more times than one would expect: mouseenter and mouseleave. These events were originally proprietary to Internet Explorer.

New to what we have seen so far in the book is Element.setStyle(). This method, along with its sibling, Element.getStyle(), do just as they suggest. They help us to get and set style properties. The syntax parallels that of addEvent() and addEvents().

Our goal for this chapter is to sit down and remove a lot of cut-and-paste code from one of our projects and replace with a very slick, object oriented roll over based on this recipe. Let's go!

主站蜘蛛池模板: 马公市| 屏山县| 平陆县| 珲春市| 清水河县| 固阳县| 牙克石市| 海兴县| 湄潭县| 日照市| 公安县| 湘潭县| 阿坝| 柘城县| 呼伦贝尔市| 华宁县| 信丰县| 班玛县| 东源县| 香河县| 南阳市| 山西省| 牡丹江市| 长宁县| 弥渡县| 平湖市| 昆明市| 剑河县| 嘉黎县| 会宁县| 航空| 满洲里市| 桦南县| 建始县| 宜昌市| 临沂市| 淮阳县| 金平| 吉安市| 尚义县| 那曲县|