05 jquery events.pptx

16
JQUERY EVENT PROGRAMMING Making Pages Come Alive with Events

Upload: rap-payne

Post on 15-Feb-2017

108 views

Category:

Technology


0 download

TRANSCRIPT

JQUERY EVENT PROGRAMMING Making Pages Come Alive with Events

Your pages can respond to events

Our pages can respond to mouse events

• click • dblclick • mouseup & mousedown

• mouseover & mouseout • hover (more later)

• mousemove

Responding to document and window events

• load • resize • scroll • unload

Keyboard events

• keypress • keydown and keyup

Event programming is a three-step process 1.  Select the element(s) 2.  Assign an event to them 3.  Pass the event a function function getResponse() { // Do something}$('#go').click(getResponse); • … or more simply … $('#go').click(function () { //Do something});

$(document).ready() •  Fires when the document loads. •  Important because jQuery involves binding events to

elements in the DOM • But you can't bind to something that doesn't exist yet •  ready() allows the binding to wait until the DOM elements

are there and loaded $(document).ready(function() { $('#aDiv').hover(function() { PopulateDiv(); });});

$(doStuff); == $(document).ready(doStuff);

hover = mouseover + mouseout •  $(selector).hover(mouseIn, mouseOut);

The event object collects data about the event that occurred •  pageX •  pageY •  screenX •  screenY •  altKey •  ctrlKey • metaKey •  shiftKey • which •  target •  data

preventDefault() prevents the normal action

Example: $('#aForm').submit(function(evt) { if (ship.status == 'onalert') { // Don't submit form evt.preventDefault(); }});

Removing events • Disassociating functions with previously-defined events $(selector).off('nameOfEvent');• Example: $('a').hover(function() { showToolTip($(this)); }, function() { hideToolTip($(this)); });$('#disable').click(function() { $('a').off('mouseover');});

You can bind other events using on() • Allows for great flexibility $(selector).on('nameOfEvent', function);

•  focusin •  focusout • select • error • scroll • contextmenu

There is no right-click, but you can simulate one with on $('selector').on('contextmenu',function(e){ e.preventDefault(); //Do all your JavaScript magic here});

tl;dr • Mouse events: click(), mouseOver(), mouseOut(), and

mouseMove() •  The document.ready() event • Keyboard events: keyPress(), keyDown(), and keyUp() •  Form element events: focus(), blur(), and change() • Event object – pageX, pageY, altKey, which, target, etc. • Preventing default behavior with e.preventDefault()