{"id":282,"date":"2018-02-23T01:03:33","date_gmt":"2018-02-23T01:03:33","guid":{"rendered":"http:\/\/pressbooks.library.ryerson.ca\/webdesign\/?post_type=chapter&#038;p=282"},"modified":"2019-04-23T21:27:31","modified_gmt":"2019-04-23T21:27:31","slug":"chapter-10-javascript","status":"publish","type":"chapter","link":"https:\/\/pressbooks.library.torontomu.ca\/webdesign\/chapter\/chapter-10-javascript\/","title":{"raw":"Chapter 9 \u2013 JavaScript","rendered":"Chapter 9 \u2013 JavaScript"},"content":{"raw":"The primary role of JavaScript is to modify the default behaviors of a web browser. Browsers come programmed with standard approaches to how a web page is rendered and interacted with. Therefore, if you wanted to add or modify an interaction, you'd need to leverage JavaScript to make this happen. Here are some examples of what can be achieved with JavaScript:\r\n<ul>\r\n \t<li>Show a <em>spinner<\/em> while the page loads (known as a pre-loader). The browser is made to overlay an image while the page renders. Once rendering is completed, the overlay is hidden and the content beneath is revealed.<\/li>\r\n \t<li>Changing how a form submits data. By overriding a form's <em>action<\/em>, the standard HTML submission is handled by JavaScript which will submit the form asynchronously (without reloading the page).<\/li>\r\n \t<li>Tracking a user as they navigate your website. JavaScript is used by analytics companies to allow page requests and interactions to be sent to a third-party website. Here are a few analytics companies that provide analytics: Google Analytics, KissMetrics, and Piwik.<\/li>\r\n \t<li>Having an interaction in one area of your website cause a response. Image sliders and carousels are examples of this. Click on a next or previous button to load a new image.<\/li>\r\n<\/ul>\r\nIt's easy to start coding your first script. All modern web browsers ship with JavaScript, so there are no external assets required to program using <em>Vanilla<\/em> or pure JavaScript. Most developers prefer to use a <a href=\"http:\/\/pressbooks.library.ryerson.ca\/webdesign\/chapter\/chapter-11-javascript-libraries\/\">JavaScript library<\/a> because they ship with many functions to simplify code. Other developers feel external libraries add a lot of unnecessary bloat since most websites use a fraction of the code available. In either case, JavaScript on its own is powerful enough to cover most use cases.\r\n\r\nPro-tip: Don't mix JavaScript up with Java. JavaScript is a web language while Java is mainly used to create applications and control embedded circuits. Until recently, JavaScript was only used for frontend or browser-based scripts. Advances in web technologies now allow it to be used on the backend using a language such as <em>Node.js<\/em>. This means you only need to know JavaScript to control browser behaviours <em>and<\/em> load content from a database and pre-process content before transferring it to the user's computer.\r\n<h2>Writing Your First Script<\/h2>\r\nThe simplest starting point is making an alert appear in the user's browser window. In the example below, an in-line <em>onclick<\/em> attribute is used to run a JavaScript alert.\r\n<pre>&lt;html&gt;\r\n&lt;body&gt;\r\n  &lt;h1&gt;Your First Script&lt;\/h1&gt;\r\n  &lt;button onclick=\"alert('Hello World!')\"&gt;Click Me&lt;\/button&gt;\r\n&lt;\/body&gt;\r\n&lt;\/html&gt;<\/pre>\r\nFigure 9-1 reveals what you would see when you click on the button:\r\n\r\n[caption id=\"attachment_365\" align=\"aligncenter\" width=\"584\"]<img src=\"http:\/\/pressbooks.library.ryerson.ca\/webdesign\/wp-content\/uploads\/sites\/25\/2018\/02\/js-hello.png\" alt=\"Hello World alert example\" class=\"wp-image-365 size-full\" width=\"584\" height=\"256\" \/> <strong>Figure 9-1<\/strong>. Javascript Alert[\/caption]\r\n\r\n<em>\u00a0<\/em>\r\n<h2>Capturing and Outputting Content<\/h2>\r\nIn this example, we will be taking content from an <em>input<\/em> field and outputting it in a <em>p <\/em>(paragraph) tag. For this to work, we will need to use the <em>id <\/em>attribute so that we can target the elements.\r\n<pre>&lt;input id=\"<strong>sometext<\/strong>\" value=\"enter anything\"&gt;\r\n&lt;button type=\"button\" onclick=\"<strong>outputText<\/strong>()\"&gt;Click&lt;\/button&gt;\r\n&lt;p id=\"<strong>output<\/strong>\"&gt;&lt;\/p&gt;\r\n\r\n&lt;script&gt;\r\nfunction <strong>outputText<\/strong>() {\r\n  document.getElementById('<strong>output<\/strong>').innerHTML = document.getElementById('<strong>sometext<\/strong>').value;\r\n}\r\n&lt;\/script&gt;<\/pre>\r\nThis time, we'd separated the script from our HTML. In the previous example, JavaScript was kept inline using the <em>onclick<\/em> attribute. By separating the JavaScript and keeping it before the closing body tag (hidden in above example), we make our code more manageable and less polluted. The <em>onclick<\/em> attribute called the JavaScript function called <em>outputText<\/em>.\r\n\r\nCan you see the relationship between the <em>id<\/em> attributes and the script? We are setting the HTML within <em>output <\/em>equal to the value of the tag <em>sometext<\/em> using their <em>id<\/em> attributes for identification. The standard is to only use an <em>id<\/em> only once on each page. An ID such as a driver's license is made to be unique to its holder. Duplicating the same ID is counterfeiting, so avoid doing it with your code.\r\n<h2>How JavaScript Works: the DOM<\/h2>\r\nIn order to make changes to the browser and the site's content, JavaScript needs access to the model used to store the browser and page's parameters. Each parameter is stored as a node in a tree or database called the <em>Document Object Model<\/em>. Each branch of the document's data is known as an object. This allows for <em>traversing <\/em>which just means that\u00a0JavaScript is tracking and accessing all tags in your HTML file. In the example of on <em>Capturing and Outputting<\/em> content, our document has several <em>id <\/em>attributes. JavaScript searches our HTML elements for a tag with the <em>id<\/em> specified.\r\n\r\nLet's break down this code, <em>document.getElementById('output').innerHTML<\/em>. Each object is separated by a period (.). The first object is the <em>document<\/em> and we're looking within it for an element with an id of <em>output<\/em>. The function in JavaScript called <em>getElementById<\/em> is what we use to traverse the document and returns it as an object. The object is composed of several attributes, one of which is the <em>innerHTML<\/em>. For an <em>input<\/em> element, we use the <em>value<\/em> attribute to access the input field's current value. If the user types something into the input field, JavaScript will capture it.\r\n\r\nAnother example of an object that we can access is the <em>window<\/em>. The window contains details on the browser's window. We can use this to capture the user's location as <em>x <\/em>and <em>y <\/em>coordinates.\r\n<h2>Mouse Location Example<\/h2>\r\nIn the following example, the <em>onmousemove<\/em> attribute is applied to the <em>html<\/em> tag. Using this method allows the function to only run when the mouse is moving anywhere on the page. If applied to the <em>body<\/em> tag, the result would be only executed on the visible contents of the page. We could have used <em>onclick<\/em> instead, but you'll find real-time updates quite satisfying compared to clicking to have the value update.\r\n\r\nThe <em>event<\/em> object is passed into the<em> showXY<\/em> function. The object provides the user's X and Y mouse position so that we can output it into the element with an <em>id<\/em> of <em>location. <\/em>In this case, it's a <em>span<\/em> element. The function sets the location span equal to <em>event.clientX + \",\" + event.clientY<\/em>. Note the use of a plus (+) sign to append a comma (,) to the value of <em>event.clientX<\/em>. A string should be encapsulated with quotes. It does not matter if it's a double quote or a single quote. However, if you want to use double quotes within your text, you'll need to encapsulate it with single quotes (and vice versa). For example, x = \"There's a small image\" and 'They said, \"upload the image\" and clicked.'\r\n\r\n[caption id=\"attachment_436\" align=\"aligncenter\" width=\"386\"]<img src=\"http:\/\/pressbooks.library.ryerson.ca\/webdesign\/wp-content\/uploads\/sites\/25\/2018\/02\/mouseXY.gif\" alt=\"Animation of mouse movement tracking with JavaScript\" class=\"wp-image-436 size-full\" width=\"386\" height=\"214\" \/> <strong>Figure 9-2<\/strong>. Mouse XY position tracking in Mozilla Firefox (v.58) using JavaScript code provided below. Courtesy Mozilla Firefox.[\/caption]\r\n<pre>&lt;!DOCTYPE html&gt;\r\n&lt;html onmousemove=\"showXY(event)\"&gt;\r\n&lt;body&gt;\r\n&lt;p&gt;XY\r\n  (&lt;span id=\"location\"&gt;0,0&lt;\/span&gt;)\r\n&lt;\/p&gt;\r\n&lt;script&gt;\r\n  function showXY(event) {\r\n    var coords = event.clientX + \",\" + event.clientY; \/\/ Setup a variable called coords\r\n    document.getElementById(\"location\").innerHTML = coords; \/\/ Output the value in #location\r\n  } \r\n&lt;\/script&gt;\r\n&lt;\/body&gt;\r\n&lt;\/html&gt;<\/pre>\r\nIt's always a good habit to provide placeholder content. In the location span, <em>0,0<\/em> is provided. This content is replaced once the current mouse position is captured by the browser and processed using the script. In cases where a user is on a slow connection or waiting for external scripts to load, the placeholder content will greet them and provide some direction.","rendered":"<p>The primary role of JavaScript is to modify the default behaviors of a web browser. Browsers come programmed with standard approaches to how a web page is rendered and interacted with. Therefore, if you wanted to add or modify an interaction, you&#8217;d need to leverage JavaScript to make this happen. Here are some examples of what can be achieved with JavaScript:<\/p>\n<ul>\n<li>Show a <em>spinner<\/em> while the page loads (known as a pre-loader). The browser is made to overlay an image while the page renders. Once rendering is completed, the overlay is hidden and the content beneath is revealed.<\/li>\n<li>Changing how a form submits data. By overriding a form&#8217;s <em>action<\/em>, the standard HTML submission is handled by JavaScript which will submit the form asynchronously (without reloading the page).<\/li>\n<li>Tracking a user as they navigate your website. JavaScript is used by analytics companies to allow page requests and interactions to be sent to a third-party website. Here are a few analytics companies that provide analytics: Google Analytics, KissMetrics, and Piwik.<\/li>\n<li>Having an interaction in one area of your website cause a response. Image sliders and carousels are examples of this. Click on a next or previous button to load a new image.<\/li>\n<\/ul>\n<p>It&#8217;s easy to start coding your first script. All modern web browsers ship with JavaScript, so there are no external assets required to program using <em>Vanilla<\/em> or pure JavaScript. Most developers prefer to use a <a href=\"http:\/\/pressbooks.library.ryerson.ca\/webdesign\/chapter\/chapter-11-javascript-libraries\/\">JavaScript library<\/a> because they ship with many functions to simplify code. Other developers feel external libraries add a lot of unnecessary bloat since most websites use a fraction of the code available. In either case, JavaScript on its own is powerful enough to cover most use cases.<\/p>\n<p>Pro-tip: Don&#8217;t mix JavaScript up with Java. JavaScript is a web language while Java is mainly used to create applications and control embedded circuits. Until recently, JavaScript was only used for frontend or browser-based scripts. Advances in web technologies now allow it to be used on the backend using a language such as <em>Node.js<\/em>. This means you only need to know JavaScript to control browser behaviours <em>and<\/em> load content from a database and pre-process content before transferring it to the user&#8217;s computer.<\/p>\n<h2>Writing Your First Script<\/h2>\n<p>The simplest starting point is making an alert appear in the user&#8217;s browser window. In the example below, an in-line <em>onclick<\/em> attribute is used to run a JavaScript alert.<\/p>\n<pre>&lt;html&gt;\r\n&lt;body&gt;\r\n  &lt;h1&gt;Your First Script&lt;\/h1&gt;\r\n  &lt;button onclick=\"alert('Hello World!')\"&gt;Click Me&lt;\/button&gt;\r\n&lt;\/body&gt;\r\n&lt;\/html&gt;<\/pre>\n<p>Figure 9-1 reveals what you would see when you click on the button:<\/p>\n<figure id=\"attachment_365\" aria-describedby=\"caption-attachment-365\" style=\"width: 584px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/pressbooks.library.ryerson.ca\/webdesign\/wp-content\/uploads\/sites\/25\/2018\/02\/js-hello.png\" alt=\"Hello World alert example\" class=\"wp-image-365 size-full\" width=\"584\" height=\"256\" srcset=\"https:\/\/pressbooks.library.torontomu.ca\/webdesign\/wp-content\/uploads\/sites\/25\/2018\/02\/js-hello.png 584w, https:\/\/pressbooks.library.torontomu.ca\/webdesign\/wp-content\/uploads\/sites\/25\/2018\/02\/js-hello-300x132.png 300w, https:\/\/pressbooks.library.torontomu.ca\/webdesign\/wp-content\/uploads\/sites\/25\/2018\/02\/js-hello-65x28.png 65w, https:\/\/pressbooks.library.torontomu.ca\/webdesign\/wp-content\/uploads\/sites\/25\/2018\/02\/js-hello-225x99.png 225w, https:\/\/pressbooks.library.torontomu.ca\/webdesign\/wp-content\/uploads\/sites\/25\/2018\/02\/js-hello-350x153.png 350w\" sizes=\"auto, (max-width: 584px) 100vw, 584px\" \/><figcaption id=\"caption-attachment-365\" class=\"wp-caption-text\"><strong>Figure 9-1<\/strong>. Javascript Alert<\/figcaption><\/figure>\n<p><em>\u00a0<\/em><\/p>\n<h2>Capturing and Outputting Content<\/h2>\n<p>In this example, we will be taking content from an <em>input<\/em> field and outputting it in a <em>p <\/em>(paragraph) tag. For this to work, we will need to use the <em>id <\/em>attribute so that we can target the elements.<\/p>\n<pre>&lt;input id=\"<strong>sometext<\/strong>\" value=\"enter anything\"&gt;\r\n&lt;button type=\"button\" onclick=\"<strong>outputText<\/strong>()\"&gt;Click&lt;\/button&gt;\r\n&lt;p id=\"<strong>output<\/strong>\"&gt;&lt;\/p&gt;\r\n\r\n&lt;script&gt;\r\nfunction <strong>outputText<\/strong>() {\r\n  document.getElementById('<strong>output<\/strong>').innerHTML = document.getElementById('<strong>sometext<\/strong>').value;\r\n}\r\n&lt;\/script&gt;<\/pre>\n<p>This time, we&#8217;d separated the script from our HTML. In the previous example, JavaScript was kept inline using the <em>onclick<\/em> attribute. By separating the JavaScript and keeping it before the closing body tag (hidden in above example), we make our code more manageable and less polluted. The <em>onclick<\/em> attribute called the JavaScript function called <em>outputText<\/em>.<\/p>\n<p>Can you see the relationship between the <em>id<\/em> attributes and the script? We are setting the HTML within <em>output <\/em>equal to the value of the tag <em>sometext<\/em> using their <em>id<\/em> attributes for identification. The standard is to only use an <em>id<\/em> only once on each page. An ID such as a driver&#8217;s license is made to be unique to its holder. Duplicating the same ID is counterfeiting, so avoid doing it with your code.<\/p>\n<h2>How JavaScript Works: the DOM<\/h2>\n<p>In order to make changes to the browser and the site&#8217;s content, JavaScript needs access to the model used to store the browser and page&#8217;s parameters. Each parameter is stored as a node in a tree or database called the <em>Document Object Model<\/em>. Each branch of the document&#8217;s data is known as an object. This allows for <em>traversing <\/em>which just means that\u00a0JavaScript is tracking and accessing all tags in your HTML file. In the example of on <em>Capturing and Outputting<\/em> content, our document has several <em>id <\/em>attributes. JavaScript searches our HTML elements for a tag with the <em>id<\/em> specified.<\/p>\n<p>Let&#8217;s break down this code, <em>document.getElementById(&#8216;output&#8217;).innerHTML<\/em>. Each object is separated by a period (.). The first object is the <em>document<\/em> and we&#8217;re looking within it for an element with an id of <em>output<\/em>. The function in JavaScript called <em>getElementById<\/em> is what we use to traverse the document and returns it as an object. The object is composed of several attributes, one of which is the <em>innerHTML<\/em>. For an <em>input<\/em> element, we use the <em>value<\/em> attribute to access the input field&#8217;s current value. If the user types something into the input field, JavaScript will capture it.<\/p>\n<p>Another example of an object that we can access is the <em>window<\/em>. The window contains details on the browser&#8217;s window. We can use this to capture the user&#8217;s location as <em>x <\/em>and <em>y <\/em>coordinates.<\/p>\n<h2>Mouse Location Example<\/h2>\n<p>In the following example, the <em>onmousemove<\/em> attribute is applied to the <em>html<\/em> tag. Using this method allows the function to only run when the mouse is moving anywhere on the page. If applied to the <em>body<\/em> tag, the result would be only executed on the visible contents of the page. We could have used <em>onclick<\/em> instead, but you&#8217;ll find real-time updates quite satisfying compared to clicking to have the value update.<\/p>\n<p>The <em>event<\/em> object is passed into the<em> showXY<\/em> function. The object provides the user&#8217;s X and Y mouse position so that we can output it into the element with an <em>id<\/em> of <em>location. <\/em>In this case, it&#8217;s a <em>span<\/em> element. The function sets the location span equal to <em>event.clientX + &#8220;,&#8221; + event.clientY<\/em>. Note the use of a plus (+) sign to append a comma (,) to the value of <em>event.clientX<\/em>. A string should be encapsulated with quotes. It does not matter if it&#8217;s a double quote or a single quote. However, if you want to use double quotes within your text, you&#8217;ll need to encapsulate it with single quotes (and vice versa). For example, x = &#8220;There&#8217;s a small image&#8221; and &#8216;They said, &#8220;upload the image&#8221; and clicked.&#8217;<\/p>\n<figure id=\"attachment_436\" aria-describedby=\"caption-attachment-436\" style=\"width: 386px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/pressbooks.library.ryerson.ca\/webdesign\/wp-content\/uploads\/sites\/25\/2018\/02\/mouseXY.gif\" alt=\"Animation of mouse movement tracking with JavaScript\" class=\"wp-image-436 size-full\" width=\"386\" height=\"214\" \/><figcaption id=\"caption-attachment-436\" class=\"wp-caption-text\"><strong>Figure 9-2<\/strong>. Mouse XY position tracking in Mozilla Firefox (v.58) using JavaScript code provided below. Courtesy Mozilla Firefox.<\/figcaption><\/figure>\n<pre>&lt;!DOCTYPE html&gt;\r\n&lt;html onmousemove=\"showXY(event)\"&gt;\r\n&lt;body&gt;\r\n&lt;p&gt;XY\r\n  (&lt;span id=\"location\"&gt;0,0&lt;\/span&gt;)\r\n&lt;\/p&gt;\r\n&lt;script&gt;\r\n  function showXY(event) {\r\n    var coords = event.clientX + \",\" + event.clientY; \/\/ Setup a variable called coords\r\n    document.getElementById(\"location\").innerHTML = coords; \/\/ Output the value in #location\r\n  } \r\n&lt;\/script&gt;\r\n&lt;\/body&gt;\r\n&lt;\/html&gt;<\/pre>\n<p>It&#8217;s always a good habit to provide placeholder content. In the location span, <em>0,0<\/em> is provided. This content is replaced once the current mouse position is captured by the browser and processed using the script. In cases where a user is on a slow connection or waiting for external scripts to load, the placeholder content will greet them and provide some direction.<\/p>\n","protected":false},"author":33,"menu_order":9,"template":"","meta":{"pb_show_title":"on","pb_short_title":"","pb_subtitle":"","pb_authors":[],"pb_section_license":""},"chapter-type":[47],"contributor":[],"license":[],"class_list":["post-282","chapter","type-chapter","status-publish","hentry","chapter-type-standard"],"part":3,"_links":{"self":[{"href":"https:\/\/pressbooks.library.torontomu.ca\/webdesign\/wp-json\/pressbooks\/v2\/chapters\/282","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/pressbooks.library.torontomu.ca\/webdesign\/wp-json\/pressbooks\/v2\/chapters"}],"about":[{"href":"https:\/\/pressbooks.library.torontomu.ca\/webdesign\/wp-json\/wp\/v2\/types\/chapter"}],"author":[{"embeddable":true,"href":"https:\/\/pressbooks.library.torontomu.ca\/webdesign\/wp-json\/wp\/v2\/users\/33"}],"version-history":[{"count":19,"href":"https:\/\/pressbooks.library.torontomu.ca\/webdesign\/wp-json\/pressbooks\/v2\/chapters\/282\/revisions"}],"predecessor-version":[{"id":663,"href":"https:\/\/pressbooks.library.torontomu.ca\/webdesign\/wp-json\/pressbooks\/v2\/chapters\/282\/revisions\/663"}],"part":[{"href":"https:\/\/pressbooks.library.torontomu.ca\/webdesign\/wp-json\/pressbooks\/v2\/parts\/3"}],"metadata":[{"href":"https:\/\/pressbooks.library.torontomu.ca\/webdesign\/wp-json\/pressbooks\/v2\/chapters\/282\/metadata\/"}],"wp:attachment":[{"href":"https:\/\/pressbooks.library.torontomu.ca\/webdesign\/wp-json\/wp\/v2\/media?parent=282"}],"wp:term":[{"taxonomy":"chapter-type","embeddable":true,"href":"https:\/\/pressbooks.library.torontomu.ca\/webdesign\/wp-json\/pressbooks\/v2\/chapter-type?post=282"},{"taxonomy":"contributor","embeddable":true,"href":"https:\/\/pressbooks.library.torontomu.ca\/webdesign\/wp-json\/wp\/v2\/contributor?post=282"},{"taxonomy":"license","embeddable":true,"href":"https:\/\/pressbooks.library.torontomu.ca\/webdesign\/wp-json\/wp\/v2\/license?post=282"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}