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

Creating a pop-up alert upon clicking a DIV

Here we will learn how to use an event listener to pop up an alert box.

Getting ready

We are familiar with how to place an HTML attribute like onmouseover that will execute upon a user's mouse entering the space of the HTML element. This is a frequent method of creating roll-over actions for buttons on website navigation. When editing a website that has these code-heavy roll overs, it can be confusing how to alter the roll overs. They create quite a bit of code.

How to do it...

Now MooTools makes our lives easy; we see that MooTools itself is becoming an oldie-and-goodie. It is exciting to learn that using listeners, heretofore a jUnGlE of confusing syntax, is now as simple as calling the addEvent() method with which MooTools has extended our elements.

<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:50px; text-align:center;">Click Me</div>
<script type="text/javascript">
var count = 0;
$('my_trigger').addEvent('click',function() {
$('my_trigger').set('html','Click Me<br/>'+(++count));
alert('Hello, please be aware that my_trigger has been clicked!');
});
</script>

How it works...

The addEvent() method takes two arguments (1) the event name and (2) the callback handler or function definition. Event names include all the common events defined by HTML; however, they each drop the "on"; for instance, instead of passing "onSubmit" as the event name, pass "submit": $('my_form').addEvent('submit',function() { return false; });.

The World Wide Web Consortium, W3C, publishes a plethora of information on events in HTML. While we might not have time to read all of it, being familiar with where it is allows us to seek out the answers to really advanced questions that will come up along the path of our development careers.

There's more...

In our example, we add an event function to my_form. Within that function we then make calls to the same element my_form. This can be reduced further by using a keyword that describes the element that is the owner of the executing function, this:

$('my_trigger').addEvent('click',function() { this.set('html','Click Me<br/>'+(++count));
...
主站蜘蛛池模板: 中超| 敦化市| 普兰店市| 新绛县| 金华市| 平遥县| 浮山县| 彭州市| 太仓市| 泸溪县| 濮阳市| 平南县| 康定县| 武功县| 鹤壁市| 桃园县| 新绛县| 新昌县| 广西| 竹溪县| 南澳县| 二连浩特市| 拉萨市| 通许县| 白水县| 个旧市| 北票市| 建宁县| 札达县| 乐业县| 越西县| 旅游| 松阳县| 博兴县| 任丘市| 石渠县| 辽阳县| 河南省| 钟祥市| 蒙城县| 深圳市|