HTML and CSS Reference
In-Depth Information
The benefit of attaching functions to objects is that the function will be able to access all of the object's prop-
erties, whereas if the function were not attached to an object the desired properties would have to be passed
to the function through parameters.
event —An event is triggered when certain conditions are met. For example, the onload event is triggered
when the page loads. There are also events for things like mouse clicks, key presses, and form submissions.
You can use event listeners to attach functions to events so that a function is executed when an event is
Awesome, aren't they! If you aren't brimming with excitement at what is possible now, don't worry. You soon will
So by now you should have a general understanding of the purpose of JavaScript and its position within the web eco-
system. Now it's time to start learning how to use JavaScript so that one day you will be able to create websites as
amazing as those demos.
The <script> Element
Before you can start writing JavaScript code, you need to know about a few housekeeping issues. The first of these is
where to put your JavaScript code. You have two options: You can either put it inline (embedding it within an HTML
file), or you can put it in a completely separate file and link to that file in your HTML. The latter method is generally
considered the better approach, and this is how you will be adding JavaScript to the Joe's Pizza Co. website.
However, there are times when inline scripts are needed, so in this section I cover both methods. Whichever method
you end up using in your projects, you are going to use the <script> element to let the browser know where your
JavaScript code is located.
Inline Scripts
JavaScript code that is embedded directly into your HTML page is referred to as inline scripts. Inline scripts are best
if you have only a short piece of JavaScript; otherwise, it will be easier to maintain your code over the long run if
you put it in its own dedicated file.
To embed JavaScript code in your HTML files, you need to place it within a <script> element. Follow these
The example code used in this chapter is available from the Chapter 10 folder in the download code files.
1. Create a new folder on your desktop called javascript-examples .
2. Now create a new file in your text editor.
3. Save this file in the javascript-examples folder as example10-1.html .
4. Copy the following code into the example10-1.html file.
<!DOCTYPE html>
Search WWH ::

Custom Search