Download presentation
Presentation is loading. Please wait.
Published byBenjamin Neal Modified over 9 years ago
1
CS 142 Lecture Notes: EventsSlide 1 Access to Event Object ● event variable (HTML): ● Passed as argument to function (DOM/Firefox): element.onclick = mouseClick; function mouseClick(evt) {... x = evt.clientX;... } ● Global variable (DOM/IE): element.onclick = mouseClick; function mouseClick() {... x = window.event.clientX;... }
2
CS 142 Lecture Notes: EventsSlide 2 Draggable Rectangle #div1 { position: absolute; }... <div id="div1" onmousedown="mouseDown(event);" onmousemove="mouseMove(event);" onmouseup="mouseUp(event);">Drag Me!
3
CS 142 Lecture Notes: EventsSlide 3 Dragging Application isMouseDown = false; function mouseDown(event) { prevX = event.clientX; prevY = event.clientY; isMouseDown = true; } function mouseMove(event) { if (!isMouseDown) { return; } element = document.getElementById("div1"); element.style.left = (element.offsetLeft + (event.clientX - prevX)) + "px"; element.style.top = (element.offsetTop + (event.clientY - prevY)) + "px"; prevX = event.clientX; prevY = event.clientY; } function mouseUp(event) { isMouseDown = false; }
4
CS 142 Lecture Notes: EventsSlide 4 Cleaner Implementation Drag Me! Drag Me Too! //<![CDATA[ new Dragger("div1"); new Dragger("div2"); //]]> }
5
CS 142 Lecture Notes: EventsSlide 5 Dragger.js, part 1 function Dragger(id) { this.isMouseDown = false; this.element = document.getElementById(id); this.element.onmousedown = this.wrap(this, "mouseDown"); } Dragger.prototype.wrap = function(obj, method) { return function(event) { obj[method](event); } Dragger.prototype.mouseDown = function(event) { this.oldMoveHandler = document.body.onmousemove; document.onmousemove = this.wrap(this, "mouseMove"); this.oldUpHandler = document.body.onmouseup; document.onmouseup = this.wrap(this, "mouseUp"); this.prevX = event.clientX; this.prevY = event.clientY; this.isMouseDown = true; }
6
CS 142 Lecture Notes: EventsSlide 6 Dragger.js, part 2 Dragger.prototype.mouseMove = function(event) { if (!this.isMouseDown) { return; } this.element.style.left = (this.element.offsetLeft + (event.clientX - this.prevX)) + "px"; this.element.style.top = (this.element.offsetTop + (event.clientY - this.prevY)) + "px"; this.prevX = event.clientX; this.prevY = event.clientY; } Dragger.prototype.mouseUp = function(event) { this.isMouseDown = false; document.onmousemove = this.oldMoveHandler; document.onmouseup = this.oldUpHandler; }
7
CS 142 Lecture Notes: EventsSlide 7 Which Element Gets Event? xyz Click on this
8
CS 142 Lecture Notes: EventsSlide 8
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.