- MooTools 1.3 Cookbook
- Jay Larry G. Johnston
- 329字
- 2021-04-02 19:07:06
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!
- JasperReports for Java Developers
- Oracle SOA Suite Developer's Guide
- UG NX 8.0基礎與實例教程
- Photoshop CC摳圖+修圖+調色+合成+特效標準培訓教程(全視頻微課版)
- Photoshop CS6從入門到精通
- MATLAB 2015從入門到精通
- AutoCAD 2020從入門到精通
- Microsoft SQL Azure Enterprise Application Development
- Photoshop海報設計技巧與實戰
- iOS智能手機APP界面設計實戰教程
- 會聲會影X8 DV影片制作/編輯/刻盤實戰從入門到精通
- WS/BPEL 2.0 for SOA Composite Applications with Oracle SOA Suite 11g
- 和秋葉一起學:秒懂Photoshop后期修圖
- OpenCms 7 Development
- Photoshop CC平面設計實戰從入門到精通