Skip to content

Instantly share code, notes, and snippets.

@6temes
Last active August 29, 2015 14:00
Show Gist options
  • Save 6temes/19e4016305e890ed5e02 to your computer and use it in GitHub Desktop.
Save 6temes/19e4016305e890ed5e02 to your computer and use it in GitHub Desktop.
Programatically create mouse events with Google Dart
import 'dart:html';
import 'dart:async';
void main() {
// Create the target element.
DivElement menuSprite = new DivElement()
..style.height = "50px"
..style.width = "50px"
..style.border = "1px solid black";
document.body.children.add(menuSprite);
// Asign event listeners.
menuSprite
..onMouseDown.listen((_) => menuSprite.style.backgroundColor = "red")
..onMouseUp.listen((_) => menuSprite.style.backgroundColor = "blue")
..onTouchStart.listen((_) => menuSprite.style.backgroundColor = "orange")
..onTouchEnd.listen((_) => menuSprite.style.backgroundColor = "brown");
document.body.onTouchStart.listen((e) {
print(e.touches[0].toString());
print(e.targetTouches[0].toString());
print(e.changedTouches[0].toString());
});
// Create the events.
// TODO: Events have more parameters or be more specific.
// See:
// * https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-dom-html.MouseEvent
// * https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-dom-html.TouchEvent
//
// CAUTION: event type is case sensitive ('mouseDown' desn't work).
MouseEvent myMouseDown = new MouseEvent('mousedown', relatedTarget: menuSprite);
MouseEvent myMouseUp = new MouseEvent('mouseup', relatedTarget: menuSprite);
// Event myTouchStart = new Event('touchstart');
// Event myTouchEnd = new TouchEvent('touchend');
// TODO: mouseMove and touchMove events.
// We can fire the events using "Element.dispatchEvent()".
new Future.delayed(new Duration(milliseconds: 500), () =>
menuSprite.dispatchEvent(myMouseDown));
new Future.delayed(new Duration(milliseconds: 1000), () =>
menuSprite.dispatchEvent(myMouseUp));
// new Future.delayed(new Duration(milliseconds: 1500), () =>
// menuSprite.dispatchEvent(myTouchStart));
// new Future.delayed(new Duration(milliseconds: 2000), () =>
// menuSprite.dispatchEvent(myTouchEnd));
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<p id="text"></p>
<script type="application/dart" src="create_custom_events.dart"></script>
<!-- for this next line to work, your pubspec.yaml file must have a dependency on 'browser' -->
<script src="packages/browser/dart.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment