Preloading and DOM DOM Table Object and JSON File Upload
Total Page:16
File Type:pdf, Size:1020Kb
Preloading and DOM DOM Table Object and JSON File upload, HTML5 File APIs Web workers web sockets and node.js jQuery, AngularJS and other libraries CMS systems Image rollover and pre-loading • An image rollover should use pre-loaded images, since viewing images that has to be downloaded take time <script> var image1, image2; function init(){ if(document.images){ image1 = new Image(); // Preload an image image1.src = "images/image1.jpg"; image2 = new Image(); // Preload a second image image2.src = "images/image2.png"; } } window.onload=init; rollover.html </script> <body> <h3>Rollover with mouse events</h3> <p>Move your mouse over the image to see the result</p> <a href="#" onMouseOver="document.rolloverImage.src=image2.src;" onMouseOut="document.rolloverImage.src=image1.src;"> <img name="rolloverImage" src="images/image1.jpg" /> </a> </body> Animation in the DOM • You can use JavaScript to create animations and effects • DOM elements (<img />, <div> or any other HTML element) can be moved around the page • The timer functions are used to create many effects • Together with certain style.* attributes as position • Other positions than relative are: static (default), absolute, fixed, inherit // This function calls function after duration milliseconds from now. var timeoutVar = setTimeout(function, duration); // This function calls function repeatedly every duration milliseconds. var timeoutVar = setInterval(function, duration); // This function clears any timer set by the functions above. clearTimeout(timeoutVar); // declare that the object have a relative position myObj.style.position= 'relative'; // Set distance from left edge of the screen. myObject.style.left = distance in pixels or points; animate.html // Set distance from top edge of the screen. myObject.style.top = distance in pixels or points; Finding elements in the DOM • To access a node in the document tree, we can use parents, children and siblings • But usually we select elements by Id, Name or Type (Tag) <!DOCTYPE html> <html> EM is a <head> sibling <title>My DOM</title> to SPAN </head> <body bgcolor="red"> <div id="myDivId" name="myDivName"></div> <script> // We could access "myDiv" by // locating the document element // (HTML), then finding its second child (BODY), // then look for its first child (DIV) document.childNodes[1].childNodes[0]; // OR going an alternate route, we could first locate the // document element (HTML) again, but then find its first child // (HEAD), then find the next child (BODY), and find its first child (DIV)" document.childNodes[0].nextSibling.childNodes[0]; // usually we however get an element by id or several elements by name or by tag name object = document.getElementById('myDivId'); // unique attribute object_collection = document.getElementsByName("myDivName"); // not unique attribute object_collection = document.getElementsByTagName('DIV'); // not unique name </script> </body></html> Select elements by CSS class or Selector • The DOM in HTML5 also defines the CSS method: getElementsByClassName() that allows us to select sets of document elements based on the identifiers in their class attribute // Find all elements that have "warning" in their class attribute var warnings = document.getElementsByClassName("warning"); • A CSS selector are the identifiers we can use in CSS – #nav (id), div (element), .warning (class) and so on • To select elements with CSS Selector we use the Document methods querySelectorAll() (returns all matching elements) or querySelector() (returns only the first matching element) // Find all elements in the document that match the selector string // and return a node list that represent all these elements var headings = document.querySelectorAll("h1,h2,h3,h4,h5,h6"); // All <div> elements plus the element with id="log" var elements = document.querySelectorAll("div,#log"); // All radio buttons in the form with id "shipping" var rbuttons = document.querySelectorAll('#shipping input[type="radio"]'); // All radio buttons with name "method" in form with id "shipping" document.querySelectorAll('#shipping input[type="radio"][name="method"]'); Modify the DOM • The first step is to - create the node (element) you wish to append and fill it with some node text. The next is to find where you wish to append it within the document. The final step is to actually do the appending (In many cases the property innerHTML can be used). • InsertBefore, replaceChild and many other operations are available // Appending a text node to #myDIV in the document var txtNode = document.createTextNode("This text was added to the DIV."); document.getElementById('myDivId').appendChild(txtNode); // To create an element var newElement = document.createElement("li"); // To create a text node var txtNode = document.createTextNode("Hello. This is a new node."); // To append the above text node to the element newElement.appendChild(txtNode); // do the actual appending to the document document.getElementById('uList').appendChild(newElement); // To create a new element with attributes var linkElement = document.createElement('a'); add-element.html linkElement.setAttribute('href', 'mypage.html'); linkElement.setAttribute('name', 'myanchor'); var newtext = document.createTextNode("This is a new link element."); linkElement.appendChild(newtext); document.getElementById('myDivId').appendChild(linkElement); XML and the DOM • We can display and update XML data with the DOM functions - before we show our markup on a page <script> var xmlDoc = loadXMLDoc("books.xml"); // get XML file via XHR, can as well be from a DB // The following code and adds an element node with a containing text node to // each <book> element in the xmlDoc (note! loop is optional and only used to change the XML data) var parentElement = xmlDoc.getElementsByTagName("book"); for (var i=0; i < parentElement.length; i++) { var newelement = xmlDoc.createElement("edition"); var newtext = xmlDoc.createTextNode("first"); newelement.appendChild(newtext); parentElement[i].appendChild(newelement); } } // The following code put the modified XML data in a table for display var titles = xmlDoc.getElementsByTagName("title"); var editions = xmlDoc.getElementsByTagName("edition"); var tableStr = "<table border='1' padding='3'>"; tableStr += "<tr><th>Title</th><th>Edition</th></tr>"; for (var i = 0; i < titles.length; i++) { tableStr += "<tr><td>" + titles[i].childNodes[0].nodeValue + "</td>"; tableStr += "<td>" + editions[i].childNodes[0].nodeValue + "</td></tr>"; } tableStr += "</table>"; document.getElementById("table").innerHTML = tableStr; </script> add-xml-element.html DOM Table Object with JSON 1 • The following example shows how to create a PHP JSON response from an AJAX search request <?php // PDO configuration searchjson.php //$dbtype = "mysql"; // XAMPP supports mysql and sqlite $dbtype = "sqlite"; $dbhost = "localhost"; $dbname = "webstore"; $dbuser = "hjo"; $dbpass = "abc123xyz"; $charset = "UTF8"; //$dsn = "$dbtype:host=$dbhost;dbname=$dbname;charset=$charset"; $dsn = "$dbtype:media.db3"; $DBH = null; class ArtCds { public $ArtistName=""; public $Title; public $Date; function __construct($Artistame="", $Title="", $Date=""){ if(!empty($Artistame)) $this->Artistame($Artistame); if(!empty($Title)) $this->Title($Title); if(!empty($Date)) $this->Date($Date); } } //get the query parameter from URL $query = $_GET["query"]; DOM Table Object with JSON 2 • PHP JSON AJAX response cont. try{ if($DBH == null) $DBH = new PDO($dsn); searchjson.php } catch (PDOException $e){ echo '<b>PDOException: </b>', $e->getMessage(); die(); } $sql = "SELECT artistname, title, date FROM artists, cds WHERE artists.artistid"; $sql .= " = cds.artistid and artists.artistname LIKE :query"; $STH = $DBH->prepare($sql); $STH->execute(array(':query' => '%'.$query.'%')); $STH->setFetchMode(PDO::FETCH_CLASS, 'ArtCds'); $notvisited = TRUE; $artcdarr = array(); while ($artcd = $STH->fetch()){ $artcdarr[] = $artcd; // put ArtCd object in array $notvisited = FALSE; } $DBH = null; if ($notvisited) $response = "No artist found with name: " . $query; else $response = json_encode($artcdarr); // serialize the objects echo $response; //output the response ?> DOM Table Object with JSON 3 • Handling the PHP JSON response with JavaScript <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Search for an artists CDs</title> searchjson.html <script> function getXmlHttpRequestObject() { if (window.XMLHttpRequest) { return new XMLHttpRequest(); // IE7 and others } else if(window.ActiveXObject) { return new ActiveXObject("Microsoft.XMLHTTP"); // IE6 and less } else { alert("Your browser doesn't support the XmlHttpRequest object!"); } } function showTable(str) { console.log(str); if (str.length == 0) { document.getElementById("myTable").innerHTML = ""; return; } var xmlHttp = getXmlHttpRequestObject(); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { console.log(xmlHttp.responseText); document.getElementById("myTable").innerHTML = ""; //clear if(xmlHttp.responseText.substr(0,2) == "No") document.getElementById("myTable").innerHTML = xmlHttp.responseText; else handleXMLHttpresponse(xmlHttp.responseText); } } var url = "searchjson.php?query=" + str + "&id=" + Math.random(); xmlHttp.open("GET", url, true); xmlHttp.send(); } DOM Table Object with JSON 4 • Handling the PHP JSON response with JavaScript cont. function handleXMLHttpresponse(json) { // document.getElementById("myTable").innerHTML = json; var jsonData = JSON.parse(json); // put the string into artistcd objects // console.log(jsonData);