Chapter 35: JavaScript Examples

DOM Navigation

Now we will look at some other techniques we can use to interact with the DOM using JavaScript. We specified we wanted to use a particular element by referencing its ID (getElementById()) but we can also interact with groups of elements that share a special type or class. To reference by type we would call the getElementsByTagName method, giving us a list of elements that we can review, or modify:

<div id="output"></div>

<input type="text" size="20"><br>

<input type="text" size="20"><br>

<input type="text" size="20"><br><br>

<input type="button" value="Submit Form">

<script>

var x=document.getElementsByTagName("input");

document.getElementById("output").innerHTML = ("Number of elements: "+x.length);

</script>

Perhaps we only want elements inside of another specific element. We can grab inputs from a particular form. To do this, we change our reference from the document as a whole to the element we want to inspect:

<div id="output"></div>

<form id="form1">

<input type="text" size="20"><br>

<input type="text" size="20"><br>

<input type="text" size="20"><br><br>

<input type="button" value="Submit Form">

</form>

<form id="form2">

<input type="text" size="20"><br>

<input type="text" size="20"><br>

<input type="text" size="20"><br><br>

<input type="button" value="Submit Form">

</form>

<script>

var x=document.getElementsByTagName("input");

document.getElementById("output").innerHTML = ("Number of elements: "+x.length+"</br>Number in form2: "+form2.getElementsByTagName("input").length;

</script>

In this example all we changed was doubling our inputs and putting them into forms. We also used form2 as our reference instead of document to create our second output, although this time we just tacked it onto the end without creating a second variable. You can see in this example that not only can we concat function results easily in JavaScript, we were still able to refer to the length() method, even though it was added to the end of the getElementsByTagName method. This chain is perfectly valid in JavaScript, and will always be evaluated from the inside out just like sets of parenthesis. In this case, counting the inputs in form2 occurred first, creating a temporary object that .length was instructed to access.

Events

It is important to keep in mind that JavaScript is not living within the confines of an object or function and will be processed as soon as it is loaded. Depending on its placement in the document this means our script may attempt to utilize something in the DOM that has not been created yet as the page is still loading. If we want our code to wait until the full page is complete, we need to wrap our code into one of these two items and then use a trigger, or event, to signify when the page is ready. One approach to this is adding an onload attribute to our body tag:

<body onload="ourFunction()">

We can even monitor events that do not involve the document itself like the location of the mouse. Monitoring the location of the mouse may have little practical application in the average website, but it can be useful in web based games and analytics applications, where knowing the position or path the mouse is on can influence how the page acts:

<script>

function getCoords(event){

var x=event.clientX;

var y=event.clientY;

alert("X: " + x + ", Y: " + y);

}

</script>

<p onmousedown="getCoords(event)">Click anywhere on this sentence to see the x and y coordinates of the mouse. Clear the alert and try again to see the numbers change.</p>

When an event we are waiting for occurs, we can react by executing other steps before it is processed, or even replace it. We can see an example of this by saying goodbye before a visitor leaves our page:

<script>

function sayGoodbye(){

alert("Thanks for visiting!");

}

</script>

<body onunload="sayGoodbye()">

To stop an event, we can use the preventDefault() method, which allows us to supersede what would have taken place. For instance, we may want to use a link to trigger a JavaScript function, but do not want to the page to reload, or follow the URL that was clicked on. In this example, we could have the following:

<script type="text/javascript">

addEventListener("load",function(){

var link= document.getElementById("google");

links.addEventListener("click",function(e){

e.preventDefault(); //prevent event action

}

});

</script>

<body>

<a href=http://www.google.com id="google">Google</a>

</body>

Geolocation

Devices and browsers that have access to GPS, cellular, or wireless router location data may provide that information to web pages (usually also in conjunction with user permission). When this data is available, our webpage can receive the information from the device. We can use it to improve the user experience, or provide features that are location dependent, like finding the nearest restaurant, or offering local deals. This example demonstrates how to access the information if it is available. Once we have the coordinates, we can write additional scripts on our backend (PHP and/or MySQL) that use them in order to tailor the user experience.

Keep in mind most browsers/devices allow the user to turn these features on and off, and not all devices will have access to or share this type of information. Because of this, it should not be a required or relied upon features unless you are sure your target users will be on such a device, and are aware that this type of feature is a requirement.

<p id="text">Where am I?</p>

<button onclick="getLocation()">Find Me</button>

<script>

var response=document.getElementById("text");

function getLocation(){

if(navigator.geolocation){

navigator.geolocation.getCurrentPosition(position);

}

else{response.innerHTML="Geolocation is not available from this device or browser.";}

}

function position(loc){

response.innerHTML="Latitude: " + loc.coords.latitude +

"<br>Longitude: " + loc.coords.longitude;

}

</script>