Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript Using JavaScript.

Similar presentations


Presentation on theme: "JavaScript Using JavaScript."— Presentation transcript:

1 JavaScript Using JavaScript

2 Document Object Model (DOM)
The DOM gives us a way to access and manipulate the contents of a document we’re focusing on its relationship with JavaScript, it is worth noting that the DOM can be accessed by other languages too, such as PHP, Ruby, Python, C++, Java, Perl, and more The DOM is a programming interface (an API) for HTML and XML pages. It provides a structured map of the document, as well as a set of methods to interface with the elements contained therein. Effectively, it translates our markup into a format that JavaScript (and other languages) can understand

3 DOM Collection of element nodes, attribute nodes, and text nodes

4 Accessing DOM Elements
The document object in the DOM identifies the page itself, and more often than not will serve as the starting point for our DOM crawling. The document object comes with a number of standard properties and methods for accessing collections of elements The example below says to look on the page ( document ), find the element that has the id value “beginner”, find the HTML content within that element ( innerHTML ), and save those contents to a variable ( foo ). var foo = document.getElementById( "beginner" ).innerHTML;

5 Accessing DOM We can access individual elements by the tags themselves using document.getElementsByTagName() This method retrieves any element or elements you specify as an argument. For example, document.getElementsByTagName("p") returns every paragraph on the page, wrapped in something called a collection or nodeList, in the order they appear in the document from top to bottom. nodeLists behave much like arrays var paragraphs = document.getElementsByTagName("p"); for( var i = 0; i < paragraphs.length; i++ ) { // do something }

6 DOM This method (getElementById) returns a single element based on that element’s ID (the value of its id attribute), which we provide to the method as an argument var photo = document.getElementById("lead-photo"); getElementsByTagName: This allows you to access nodes in the document based on the value of a class attribute. This statement assigns any element with a class value of “column-a” to the variable firstColumn so it can be accessed easily from within a script. var firstColumn = document.getElementsByClassName("column-a"); Like getElementsByTagName , this returns a nodeList that we can reference by index or loop through one at a time.

7 DOM querySelectorAll allows you to access nodes of the DOM based on a CSS-style selector. The syntax of the arguments in the following examples should look familiar to you. It can be as simple as accessing the child elements of a specific element: var sidebarPara = document.querySelectorAll(".sidebar p"); Like getElementsByTagName and getElementsByClassName , querySelectorAll returns a nodeList (even if the selector matches only a single element) To get the value of an attribute attached to an element node, we call getAttribute() with a single argument: the attribute name var bigImage = document.getElementById("lead-image"); alert( bigImage.getAttribute("src") ); // Alerts "stratocaster.jpg"

8 Manipulating DOM setAttribute(): To continue with the previous example, we saw how we get the attribute value, but what if we wanted to set the value of that src attribute to a new pathname altogether? Use setAttribute() ! This method requires two arguments: the attribute to be changed and the new value for that attribute. In this example, we use a bit of JavaScript to swap out the image by changing the value of the src attribute. var bigImage = document.getElementById("lead-image"); bigImage.setAttribute("src", "lespaul.jpg"); What it’s used for: Update checked attributes of checkboxes and radios Changing href of link elements to load different style sheets Update title attribute of an element

9 Manipulating DOM innerHTML: innerHTML gives us a simple method for accessing and changing the text and markup inside an element var introDiv = document.getElementsByClassName("intro"); introDiv.innerHTML = "<p>This is our intro text</p>"; DOM also allows us to read and or change style rules using the style property of DOM elements var para = document.getElementById(“intro”); para.style.color=“blue”; -CSS properties with hyphens (like background-color) become backgroundColor (camel case)

10 Adding and Removing Elements
To create a new element, use the aptly named createElement() method. This function accepts a single argument: the element to be created var newDiv = document.createElement("div"); To create a text element, call the createTextNode() method. To use it, provide a string of text as an argument, and the method creates a DOM-friendly version of that text var ourText = document.createTextNode("This is our text.");

11 Adding and Removing Elements
To add newly created elements to the DOM, use the appendChild() method. It is called on the element that is to be the parent of the newly created element For example: <div id=“our-div”></div> var ourDiv = document.getElementById("our-div"); var newParagraph = document.createElement("p"); var copy = document.createTextNode("Hello, world!"); newParagraph.appendChild( copy ); ourDiv.appendChild( newParagraph ); Other methods of adding/removing elements are listed below. Look up their usage insertBefore() replaceChild() removeChild()

12 Polyfill Polyfill is a term coined by Remy Sharp to describe a JavaScript “shim” that normalizes differing behaviour from browser to browser An HTML5 shiv/shim is used to enable Internet Explorer 8 and earlier to recognize and style newer HTML5 elements such as article, section, and nav Modernizr isn’t a polyfill in and of itself, but rather a test suite that can be used to detect the presence of browser features and load polyfills as needed Selectivizr allows older versions of Internet Explorer to understand complex CSS3 selectors such as :nth-child and ::first-letter Respond.js is a fast and lightweight polyfill that allows older browsers (again, most commonly Internet Explorer 8 and below) to understand min-width and max-width media queries, which are commonly used in responsive designs

13 JavaScript Libraries A JavaScript library is a collection of prewritten functions and methods that you can use in your scripts to accomplish common tasks or simplify complex ones Aside: They can simplify AJAX (Asynchronous JavaScript and XML) which is a way of dynamically loading content from a server without refreshing the whole page Drawback of libraries: Users might be forced to download code that never gets executed. Developers are away and are making their codes modular

14 JavaScript Libraries jQuery (jquery.com): the most popular library. It is free, open-source, and has a syntax easy to understand for those with CSS, JavaScript, and DOM experience. Dojo (dojotoolkit.org): this is an open source, modular toolkit that is particularly helpful for developing web applications with Ajax YUI (yuilibrary.com). The Yahoo! User Interface Library is another free, open source JS library for building rich web applications. It is part of The YUI Library project at Yahoo! Many others exists

15 How to use jQuery Download from jquery.com and include in your code
<script src="pathtoyourjs/jquery min.js"></script> Most scripts modify the DOM, the scripts need to wait for the DOM to finish loading Always start your scripts with: <script> $(document).ready(function(){ // Your code here }); </script>

16 Scripting with jQuery jQuery simplifies selecting a DOM element
var paragraph = document.getElementById( "status" ); Using jQuery: var paragraph = $("#status"); You want to find everything with a class of “header”? Use $(".header"); . By the element’s name? Sure: $("div"); . Every subhead in your sidebar? Easy-peasy: $("#sidebar .sub"); You can even target elements based on the value of attributes: $("[href='

17 Scripting with jQuery jQuery also allows us to chain objects together in a way that can target things even CSS can’t (an element’s parent element, for example). Let’s say we have a paragraph and we want to add a class to that paragraph’s parent element. We don’t necessarily know what that parent element will be, so we’re unable to target the parent element directly. In jQuery we can use the parent() object to get to it. $("p.error").parent().addClass("error-dialog"); Another major benefit is that this is highly readable at a glance: “find any paragraph(s) with the class “error” and add the class “error-dialog” to their parent(s).”

18 Some jQuery Effects .animate(): Perform a custom animation of a set of CSS properties. $("button").click(function(){     $("div").animate({left: '250px'}); }); .hide(): Hide the matched elements. $("#show").click(function(){     $("p").hide(); }); .slideToggle(): Display or hide the matched elements with a sliding motion


Download ppt "JavaScript Using JavaScript."

Similar presentations


Ads by Google