3.12: JavaScript Examples
- Page ID
- 3691
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)
( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\id}{\mathrm{id}}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\kernel}{\mathrm{null}\,}\)
\( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\)
\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\)
\( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)
\( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)
\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)
\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vectorC}[1]{\textbf{#1}} \)
\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)
\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)
\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)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 ></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 ></div> <form > <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 > <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 weconcat
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 of the mouse 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>
While we are waiting for an event to occur, we can execute 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 >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 >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>