Events & Listeners
Events & Listeners
studio
events & listeners
Daniel Jackson
1
event classification
Event
button
Int Mouse Keyboard HTML
!
function
!
Function
! function
Function
Activation
! event !
? target type !
Node Event EventType
4
attaching listeners in JQuery
execute handler when document DOM is ready
› $(document).ready(handler) or just $(handler)
execute handler when element is clicked
› element.click(handler)
› element.bind(‘click’, handler)
execute handler depending on event type
› element.bind({keydown: handler1, keyup: handler2})
can also trigger event manually
› element.trigger(‘myevent’)
5
listener uses event property
<head>
<script>
$(function () {
$(document).bind('mousemove',
function(e){
$('#log').text("x: " + e.pageX
+ ", y: " + e.pageY)});
})
</script>
</head>
<body>
<div id=log></div><br>
</body>
6
listener acts on global variables
<head>
<script>
$(function () {
var ds = $('#dollars');
var es = $('#euros');
var EUROS_PER_DOLLAR = 0.755;
var convert = function (x, rate) {
return (x * rate).toFixed(2);};
ds.change(function () {
es.val(convert(ds.val(), EUROS_PER_DOLLAR));});
es.change(function () {
ds.val(convert(es.val(), 1/EUROS_PER_DOLLAR));});
});
</script>
</head>
<body>
Dollars:<input id=dollars></input><br>
Euros:<input id=euros></input>
</body>
7
listener uses local variable
<head>
<script>
$(function () {
var b = $('#button');
b.click(
(function (i) {
return (function () {
i += 1;
$(this).text("Pressed " + i + " times");
});
}) (0));
})
</script>
</head>
<body>
<button id=button>Press me!</button>
</body>
8
element created with listener
<head>
<script>
$(function () {
var fromTo = function (from, to, f) {
for (var i = from; i <= to; i = i+1) f(i);
};
9
what’s wrong with this?
<head>
<script>
$(function () {
for (var i = 0; i <= 3; i += 1) {
var bi = $("<button>"); bi.text(i);
$('body').append(bi);
bi.click(function () {
$('#log').text("Pressed " + i);});});
};
})
</script>
</head>
<body>
<div id=log></div>
</body>
10
event propagation
defaultView
document
› Netscape: capturing
› Microsoft: bubbling
<html>
› W3C: support both
<body>
› IE8: still only bubbling
› JQuery, bubbling only
Capture Phase (1) Bubbling Phase (3)
<table>
› end bubbling with
<tbody>
event.stopPropagation()
<tr> <tr>
11
MIT OpenCourseWare
http://ocw.mit.edu
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.