05 jquery events.pptx
TRANSCRIPT
Our pages can respond to mouse events
• click • dblclick • mouseup & mousedown
• mouseover & mouseout • hover (more later)
• mousemove
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(); });});
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()