43
Dynamic HTML

Dynamic HTML. A combination of technologies to create dynamic web pages – xhtml – CSS – Javascript Browsers make the page that is being displayed, its

Embed Size (px)

Citation preview

Dynamic HTML

Dynamic HTML

• A combination of technologies to create dynamic web pages– xhtml– CSS– Javascript

• Browsers make the page that is being displayed, its style properties, and events accessible to JavaScript.

The DOM

• A platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content and structure of HTML and XHTML documents

• every element in the HTML document is represented by an object

• Elements can be manipulated using the properties and methods of the corresponding objects

• Changes in the element properties are immediately reflected by the browser

The DOM

DOM Standards

• W3C www.w3.org defines the standards• DOM Level 3 recommendation

– www.w3.org/TR/DOM-Level-3-Core/• DOM Level 2 HTML Specification

– www.w3.org/TR/DOM-Level-2-HTML/– additional DOM functionality specific to HTML, in

particular objects for XHTML elements

• But, the developers of web browsers– don't implement all standards – implement some standards differently– implement some additional features

Accessing HTML Elements

• All HTML elements (objects) are accessed through the document object

• document itself is automatically created• Several ways to access a specific element

– paths in the DOM tree– retrieval by tag– retrieval by ID

Accessing Elements by Tags

<p>This <span>example</span> is lovely.</p>

<p>But <span>this one</span>is even more!</p>

function execute() {

var spans = document.getElementsByTagName("span");

spans[0].style.color="red";

spans[1].style.color="blue";

spans[1].style.fontVariant="small-caps";

}

body

head

Accessing Elements by ID

<div id="div1"> This text can be hidden!</div>

function execute() {

var theDiv = document.getElementById("div1");

if (theDiv.style.visibility=="hidden")

{theDiv.style.visibility="visible" }

else {theDiv.style.visibility="hidden" }

} head

This technique is more stable w.r.t. document changes (why?)

body

Element Properties

• Elements of different types have different sets of properties and methods

• See www.w3schools.com/htmldom/ for a detailed list of element properties and methods

• Most elements have the style member• style is an object that represents the style-

sheet rules applied over the element

Other Node Properties• nodeType property

• ELEMENT_NODE: HTML element• TEXT_NODE: text within a parent element• ATTRIBUTE_NODE: an attribute of a parent element

– attributes can be accessed another way• CDATA_SECTION_NODE

– CDATA sections are good for unformatted text

– nodeName property– nodeValue property– attributes property– innerHTML property

• not standard, but implemented in major browsers • very useful

– style property• object whose properties are all style attributes, e.g., those defied in CSS

The innerHTML Property

• The attribute innerHTML attribute of an element is the HTML code embedded inside that element

• Hence, you can replace existing content by setting this attribute:– element.innerHTML = "new HTML code”

function replace(button) {d = document.getElementById("d1");

d.innerHTML = "<h1>This is a header<\/h1>";

button.disabled=true;}

Special DOM Objects

• window– the browser window– new popup windows can be opened

• document– the current web page inside the window

• body– <body> element of the document

• history– sites that the user visited– makes it possible to go back and forth using scripts

• location– URL of the document– setting it goes to another page

Events

Event Example<html>

<head>

<title>Simple Events</title>

<script type="text/javascript">

function focusInput() {

var theInput = document.getElementsByTagName("input")[0]

theInput.style.background="yellow" }

function blurInput() {

theInput = document.getElementsByTagName("input")[0]

theInput.style.background="white" }

</script>

</head>

Event Example (cont)

<body> <p> <img src="lighton.gif" alt="light bulb" onmouseover="alert('Mouse Over')" /> </p> <p> <input type="text" onfocus="focusInput()"

onblur="blurInput()" /> </p> </body></html>

Event Model

• Events usually occur due to users actions– For example, pressing the keyboard, changing a

text field, moving the mouse over an element, etc.• An event is represented by an event object

that is created upon the event occurrence• Every event has an associated target element

– For example, the image over which the mouse clicks

Event Model (cont)

• Elements can have registered event listeners which are associated with certain types of events

• When an event takes place, the listeners that are registered for this event are invoked

• Typically, a listener is described by a scripting code (e.g., JavaScript)– This code is executed upon listener invocation

Inline Listener Registration

• The simplest (and most common) way to register a listener is by an attribute assignment:

ontype = "JavaScript code"• For example:

<img src="img.gif" onmouseover="alert('!')" />• The JavaScript code has access to the following

objects:– this - the element (e.g., the image defined above)– event - the event object

Some Event Types

loadunloadabort

clickdblclick

mousedownmousemove mouseup mouseover

resetselectsubmit

changeblur

focus

keydownkeypress

keyup

Another Example<html>

<head><title>Event Object Example</title>

<script type="text/javascript">

function execute(e) {

alert(" x: " + e.clientX + ", y: " + e.clientY +

" mouse button: " + e.button); }

</script></head>

<body onmousedown="execute(event)"

style="cursor: pointer;

position:absolute; width:100%; height:100%"> </body>

</html>

JQuery

JQuery

• Open source library for manipulating the DOM• JQuery object has functions for

– Selecting DOM elements– Manipulating DOM elements– Event handling– Effects and Animations– AJAX– Utilities

• Simple way into dynamic HTML

jQuery Object

• jQuery– Most often seen as $

• $ is a legal identifier in JavaScript

– Better, cleaner to use jQuery• Can be used as a function and as an object

– JQuery function is used to select DOM elements– jQuery object is used for utility functions

• Includes a way to define a function that will run when the page is fully loaded

jQuery document ready

• Function that is called when page is loaded• jQuery(document).ready(function() {

// Javascript});

• Can be placed anywhere

<html><head><title>jQuery Hello World</title> <script src="/libs/jquery.js"></script><script>function tryMe(){

jQuery("#buttondiv").html("You pushed my button");}</script>

</head><body> <script> $(document).ready(function(){ $("#msgid").html("This is Hello World by JQuery");}); </script> This is Hello World by HTML<button id="mybutton" onclick="tryMe();">Try Me</button> <div id="msgid"></div><div id="buttondiv"></div> </body></html>

jQuery Selector

• Select DOM elements by– HTML element tag jQuery(“p”)– HTML element class

jQuery(“.class”)– HTML element id

jQuery(“#id”)– More advanced selectors

• Selector returns the elements as a JavaScript object– Methods for manipulating the elements

jQuery Selector

• $(selector)• selector:

– $(‘#id’) id of element– $(‘p’) tag name– $(‘.class’) CSS class– $(‘p.class’) <p> elements having the CSS class– $(‘p:first’) $(‘p:last’) $(‘p:odd’) $(‘p:even’)– $(‘p:eq(2)’) gets the 2nd <p> element (1 based)– $(‘p’)[1] gets the 2nd <p> element (0 based)– $(‘p:nth-child(3)) gets the 3rd <p> element of the parent. n=even, odd too.– $(‘p:nth-child(5n+1)’) gets the 1st element after every 5th one– $(‘p a’) <a> elements, descended from a <p>– $(‘p>a’) <a> elements, direct child of a <p>– $(‘p+a’) <a> elements, directly following a <p>– $(‘p, a’) <p> and <a> elements– $(‘li:has(ul)’) <li> elements that have at least one <ul> descendent– $(‘:not(p)’) all elements but <p> elements– $(‘p:hidden’) only <p> elements that are hidden– $(‘p:empty’) <p> elements that have no child elements

Useful jQuery Functions• .each() iterate over the set• .size() number of elements in set• .end() reverts to the previous set• .get(n) get just the nth element (0 based)• .eq(n) get just the nth element (0 based) also .lt(n) & .gt(n)• .slice(n,m) gets only nth to (m-1)th elements• .not(‘p’) don’t include ‘p’ elements in set• .add(‘p’) add <p> elements to set• .remove() removes all the elements from the page DOM• .empty() removes the contents of all the elements• .filter(fn/sel) selects elements where the func returns true or sel• .find(selector) selects elements meeting the selector criteria• .parent()returns the parent of each element in set• .children() returns all the children of each element in set• .next() gets next element of each element in set• .prev() gets previous element of each element in set• .siblings() gets all the siblings of the current element

Other Functions

• Formatting Functions– .css(property, value)– .html()– .val() (form elements)– .text()– .addClass(‘class’)– .removeClass(‘class’)

• Adding Elements– $(‘#target’).before(‘<p>Inserted before #target</p>’);– $(‘#target’).after(‘<p>This is added after #target</p>’);– $(‘#target’).append(‘<p>Goes inside #target, at end</p>’);– $(‘#target’).wrap(‘<div></div>’);

Example 1

• Compare the following:

What are the advantages of the jQuery method?

$("a").click(function(){alert("You clicked a link!");

});

<a href="#" onclick="alert(‘You clicked a link!')">Link</a>

Example 2

<script>$("h2").click(function(){

$(this).hide("slow");});

</script> What will this do?

What happens if you have more than one

h2?

Try it!

Example 3

<script>$("#btnHideBlue").click(function(){

$("p.blue").hide("slow");});

</script>

Hide all blue paragraphs when btnHideBlue is clicked

<button id='btnHideBlue'>Hide Blue</button>

jQuery EventsEvent Method Description

$(selector).click(function) Invokes a function when the selected elements are clicked

$(selector).dblclick(function) Invokes a function when the selected elements are double-clicked

$(selector).focus(function) Invokes a function when the selected elements receive the focus

$(selector).mouseover(function) Invokes a function when the mouse is over the selected elements

$(selector).keypress(function) Invokes a function when a key is pressed inside the selected elements

For a full jQuery event reference, please see jQuery Events Reference

Example 4

<script> $("#lemon").mouseover(function(){ $(this).append(" Cookie! ");

});</script>

Append text to paragraph lemon on mouseover

<p id='lemon'>Lemon drops biscuit chocolate…</p>

Manipulating CSS

CSS Properties Description

$(selector).css(propertyName) Get the style property value of the first selected element

$(selector).css(propertyName,value) Set the value of one style property for selected elements

$(selector).css({properties}) Set multiple style properties for selected elements

$(selector).addClass(class) Apply style class to the selected elements

For a full jQuery CSS reference, please see jQuery CSS Methods ReferenceFor more on the css function, see http://api.jquery.com/css/

Example 5

<script> $("#btnColor").click(function(){ $("#lemon").addClass("blue"); });</script>

Change color of paragraph lemon when btnColor is clicked

<style type="text/css">.red{

color:red;}.blue{

color:blue;}

</style>

Example 6

Display the color of the paragraph lemon when

btnColorCheck is clicked.

What color is the paragraph?

<script>$("#btnColorCheck").click(function(){ alert($("#lemon").css("color"));});

</script>

Example 7

<script>$("p").dblclick(function(){

$(this).css("background-color", "yellow");});

</script>

Highlight (background-color = yellow) any paragraph that is double-clicked

jQuery EffectsFunction Description

$(selector).hide() Hide selected elements

$(selector).show() Show selected elements

$(selector).toggle() Toggle (between hide and show) selected elements

$(selector).slideDown() Slide-down (show) selected elements

$(selector).slideUp() Slide-up (hide) selected elements

$(selector).slideToggle() Toggle slide-up and slide-down of selected elements

$(selector).fadeIn() Fade in selected elements

$(selector).fadeOut() Fade out selected elements

$(selector).fadeTo() Fade out selected elements to a given opacity

$(selector).fadeToggle() Toggle between fade in and fade out

Example 8

<script> $("#btnToggle").click(function(){ $("#lemon").slideToggle("slow"); });</script>

Create a toggle buttonthat shows/hides paragraph lemon.

Example 9

<script> $("#btnFade").click(function(){ $("#lemon").fadeTo("slow", 0.5); });</script>

Fade paragraph lemon to 50% opacity when

btnFade is clicked.

Manipulating HTML

Function Description

$(selector).html(content) Changes the (inner) HTML of selected elements

$(selector).append(content) Appends content to the (inner) HTML of selected elements

$(selector).after(content) Adds HTML after selected elements

For a full jQuery HTML reference, please see jQuery HTML Methods Reference

Example 10

<script> $("#btnReplace").click(function(){ $("#lemon").html("Lollipop soufflé ice

cream tootsie roll donut..."); });</script>

Replace text in paragraph lemon when btnReplace

is clicked.