lecture 5 - penn engineeringcis197/lectures/pdfs... · the event handler api is pretty easy to work...

Post on 09-Jul-2020

1 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Lecture 5JavaScript in the Browser

1 / 28

Agenda1. The DOM2. jQuery3. Browser Events

2 / 28

Warm-up: Loading JavaScriptIn Node, we used to load JavaScript files. Inthe browser, we need to use a special tag.

Browsers load tags sequentially, so it's good practice to put thescript tags last. That way users will see the bare-bones HTML pagemore quickly.

require('module')<script>

<body><!-- content and stuff --><script src="path/to/script.js"></script></body>

3 / 28

The DOM

4 / 28

DOM BasicsDOM = Document Object ModelTree of JavaScript objects representing the HTMLdocument

Called DOM nodesAllows you to dynamically change the page usingJavaScript

5 / 28

HTML

<!DOCTYPE html><html> <head></head> <body> <p>I'm a paragraph.</p> <div>And I'm a div!</div> </body></html>

DOM Tree

6 / 28

Chrome Dev ToolsAlt + ⌘ + j in Chrome will let you access, visualize,and maniupulate the DOM

You can also right click and hit 'Inspect Element'to go straight to a specific node

Other modern browsers have dev tools as well - getfamiliar with the toolset in your browser of choice,and you'll be able to debug a lot more effectively!

7 / 28

The "Vanilla DOM"There is a native DOM API, but it's notoriously verboseand annoying to work with. It's very uncommon towrite DOM manipulation code without using a library.

var node = document.body.firstChild;

if (node.nodeType === 3) { // Text node console.log('Content: ' + node.nodeValue);} else { // Regular node var n = node.childNodes.length; console.log('Tag: <' + node.nodeName + '>'); console.log('Number of children: ' + n);}

8 / 28

jQueryOr: The Almighty $

9 / 28

About jQueryOptimized, abstracted DOM manipulationIntuitive API and method syntaxExpressive syntax driven by CSS selectorsPretty good syntax for web requestsWorks in nearly all browsersProbably the most popular JavaScript library ever

10 / 28

jQuery ObjectsThe basic currency of jQuery is a jQuery object, a wrapper for DOMnodes and allows you to efficiently manipulate them. You can findelements to make into a jQuery object by using CSS selectors.

1. - searches the whole document for nodes thatmatch the selector

2. - only finds children of that match the selector

You can make a 'vanilla' DOM node into a jQuery object with . In fact, jQuery does this internally;

is the same as calling .

$(selector)

$someNodes.find(selector)$someNodes

$(vanillaNode) $(selector)$(document).find(selector)

11 / 28

jQuery Selector Examples// IDvar $myEl = $('#myEl');

// Tag namevar $allTables = $('table');

// Descendant of IDvar $lessons = $('#content lesson');// Equivalently:$lessons = $('#content').find('lesson');

// Pseudo-selectorsvar $oddInputs = $('input:odd');

12 / 28

Simple jQuery Examplehttp://jsfiddle.net/webdevem/Q8KVC/

13 / 28

ChainingjQuery achieves a visually pleasing API through methodchaining. This is accomplished through clever use of a

pointer.this

// Note: $.fn === $.prototype$.fn.empty = function () { var elem, i = 0;

for (; (elem = this[i]) != null; i++) { elem.innerHTML = ''; }

return this;};

14 / 28

Creating Elements withjQueryYou can create elements with jQuery just by passing inan HTML tag string. For example:

This is pretty cool because it allows you to build a pagedynamically.

$span = $('<span>').text('I am span.');$myDiv.append($span);

15 / 28

Browser Events

16 / 28

Browser Event BasicsUser interactions are modelled with an event-based system;browsers have a JavaScript API to hook into these events.Just like the event listeners we looked a few weeks ago -functions are registered as event listeners and receive argumentswith event information (e.g. which key was pressed).Many different event types:

Mouse: mousedown, mouseup, click, dblclick, mousemove,mouseover, mousewheel, mouseout, contextmenuTouch: touchstart, touchmove, touchend, touchcancelKeyboard: keydown, keypress, keyupForms: focus, blur, change, submitWindow: scroll, resize, hashchange, load, unload

17 / 28

Handlers in HTMLIt's technically possible to define event handlersdirectly in your HTML like so:

This is fine when there's only one simple event on apage - say, a login form with validation. It is not a goodidea to do this in any other context; JavaScript codeshould stay in files, separate from the markup.

<button class="submit" onclick="submitForm();"> Submit</button>

.js

18 / 28

Handlers in JavaScriptThe event handler API is pretty easy to work with, even withoutjQuery. Don't worry, we'll get to jQuery in a few slides - but let's usethe Vanilla DOM for a little while:

With this syntax, the submit button handler becomes:

domNode.addEventListener(eventType, eventListener);

var buttons = document.getElementsByTagName('button');

buttons[0].addEventListener('click', function () { submitForm();});

19 / 28

Event ObjectsEvent handlers are passed an event object with the properties of therelevant event. For example, a mouse event would have and properties indicating the mouse coordinates.

Many events also have a property containing the triggeringDOM node, which makes it much easier to reuse listeners.

clientXclientY

target

document.addEventListener('click', function (e) { console.log('X: ' + e.clientX); console.log('Y: ' + e.clientY); console.log('Target: ' + e.target);});

20 / 28

Cross-Browser SadnessIE8 and below use a completely different API for attaching events:

Plus, the callback gets no event object - the properties are attachedto a global event object called .

If only there were a better, cross-browser way...

domNode.attachEvent('onclick', function () { // do stuff});

window.event

21 / 28

Events with jQueryOnce again, jQuery provides a convenient solution to a DOM-related problem. You can bind handlers to jQuery objects usingmethods corresponding to the event type: click(), mousein(), keyup()...

$('button').click(function (e) { // Triggering node passed as "this" context $(this).attr('hovered', true);});

22 / 28

jQuery Event ObjectsjQuery event objects have all the same objects as thestandard DOM events. However, they're nowstandardized across browsers, which is veryconvenient.

Also, in jQuery events, the triggering node is availableas , which is quite useful.this

23 / 28

Propagation (Bubbling)Events don't stop on the initially-triggering element. They "bubbleup," or propagate, up the DOM tree until they get to the root (

). Consider the example of clicking one of the links in theHTML below:

The click handlers will run first, followed by handlers,and finally handlers - one of which follows the link.

document

<body> <a href="/foo">foo</a> <a href="/bar">bar!</a></body>

<a> <body>document

24 / 28

Stopping PropagationYou can call to ignore onlythe browser-specific functionality (like navigating to apage), or to stop thebubbling entirely.

Live example

event.preventDefault()

event.stopPropagation()

// Prevent users from clicking links to navigate$('a').click(function (e) { e.preventDefault();});

25 / 28

Advanced jQuery EventsThe method is a more general way of handling jQuery events.The simplest version you've seen before: it registers a listener for agiven name. But there is also a three-argument version, which runsthe listener when any matching descendent of the parent nodereceives the event.

on()

// Run handler on existing matching elements$('#menu option').on('hover', onHover);

// Run handler on any children of #menu// that match the selector$('#menu').on('option', 'hover', onHover);

// Run handler on any nodes in the entire document// which match the selector$(document).on('#menu option', 'hover', onHover);

26 / 28

Document Ready EventAfter a browser parses an HTML document, it must do work to layout elements on the page. There's a delay (only a few milliseconds)between content first appearing and the DOM actually being ready.If your JavaScript tries to manipulate the page before it's ready, itwon't work!

Your best bet, again, is to use jQuery to hook into the document'sready state event:

$(document).ready(function () { // Do stuff});

// Equivalent, preferred syntax$(function () { // Do stuff});

27 / 28

Up NextHomework 4 - Pokémon Map Builder

HTML/CSS, DOM, jQuery, and eventsDue Sunday, February 28 at 11:59:59pmOne of the most fun homeworks - but startearly!

Next time: Backbone.js

28 / 28

top related