11,99 €
This book shows off JavaScript's potential for developing web applications by mixing in-depth theory instruction with enjoyable assignments that will push your limits. To gain a thorough knowledge of the ideas, you can experiment with them in your own editor or browser console as you learn them. Basic programming concepts, including variables, arrays, objects, functions, conditionals, loops, classes, and more, will be covered first. Building on this foundation, you'll combine JavaScript with HTML and CSS to create interactive web applications that you can use immediately away, with the help of interesting examples and practical exercises. The fundamentals of the JavaScript language will be used to help you learn how to create your own scripts from scratch, which will make the script-writing process easier. Detailed examples and scripts explaining how to combine JavaScript with Google Apps script were provided in Chapters Sixteen and Seventeen. Creating and releasing add-ons for Google Sheets, Docs, and Forms on an online shop is made simple using Apps Script. It functions as a unified platform for creating, coding, and eventually sharing apps on the web store. The concepts of creating a menu, sending emails, developing interactive web pages, creating a user login and registration form, submitting HTML form data to Google Sheets, searching Google Sheets content from a website, and putting all of these strategies into practice to create an interactive web page that serves as a form to submit sheets will all be covered.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Veröffentlichungsjahr: 2025
JAVASCRIPT
A Comprehensive Manual for Creating Dynamic, Responsive Websites and Applications That is Suitable for Both Novices and Experts.
ALL RIGHTS RESERVED
No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the copyright holder.
Ibrahim Nugwa Abdulrazak has legally established his right to be named as the author of the editorial content in this work.
For more information on Noogul Product’s, customer service, and our editorial offices across the world, send an email to: [email protected]
Noogul also offers its books in print-on-demand and a range of electronic formats. This book's normal print versions may contain certain content that isn't accessible in other media.
Copyright © IBRAHIM N.A
First Published, 2024
Noogul Digital Publishing
(RC 3185897)
Registered Office(s): Block No. B34 Along PZ Area, Sabon Gari Zaria, Kaduna State - Nigéria.
This tutorial is designed for the aspiring Web Designers and Developers with a need to understand JavaScripting in enough detail along with its simple overview, and practical examples. This tutorial will give you enough ingredients to start with JavaScript from where you can take yourself at higher level of expertise.
Before proceeding with this tutorial you should have a basic working knowledge with Windows or Linux operating system, additionally you must be familiar with:
Experience with any text editor like notepad, notepad++, or Edit plus etc.
Have Basic and Advanced Knowledge of HTML.
How to create directories and files on your computer.
How to navigate through different directories.
How to type content in a file and save them on a computer.
Understanding about images in different formats like JPEG, PNG format.
Knowledge of How to use Google Sheets (Excel Sheet).
Audience
Prerequisites
Chapter One
Features of JavaScript
Uses of JavaScript
1. Web Applications
2. Web Development
3. Mobile Applications
4. Game
5. Presentations
6. Server Applications
7. Web Servers
Application of JavaScript
Prerequisite to Writing Your First JavaScript program
Running JavaScript in the Browser Window
Using JavaScript in an HTML event attribute
Using JavaScript in a script element
Script placement and JavaScript execution
Creating a .js file
External References
Chapter Two
JavaScript Basics
JavaScript Can Change HTML Content
JavaScript Can Change HTML Attribute Values
JavaScript Can Change HTML Styles (CSS)
JavaScript Can Hide HTML Elements
JavaScript Can Show HTML Elements
The <script> Tag
JavaScript Functions and Events
JavaScript in <head> or <body>
JavaScript in <head>
JavaScript in <body>
JavaScript Expressions
JavaScript Display Possibilities
Using innerHTML
Using document.write()
Using window.alert()
Using console.log()
JavaScript Print
JavaScript Statements
JavaScript Programs
JavaScript Statements
JavaScript White Space
JavaScript Line Length and Line Breaks
JavaScript Code Blocks
JavaScript Keywords
JavaScript Values
JavaScript Literals
Chapter Three
JavaScript Comment
Types of JavaScript Comments
JavaScript Single line Comment
JavaScript Multi line Comment
Using JavaScript Comments to Prevent Code Execution
Commenting Out Function Calls
Commenting Out Function Bodies — Without Return Values
Commenting Out Function Bodies — With Return Values
Writing Effective JavaScript Comments
Chapter Four
JavaScript Variable
JavaScript Keywords
JavaScript Variable Naming Convention
JavaScript Var Keyword
Example using var
Note:
JavaScript Let Keyword
JavaScript Const Keyword
When to Use JavaScript const?
JavaScript Local Variable
Function Scope
JavaScript Global Variable
Internals of global variable in JavaScript
Automatically Global
Global Variables in HTML
How to use variables
Where to use which variable
Chapter Five
JavaScript Operators
JavaScript Assignment
Assignment Examples
JavaScript Arithmetic Operators
JavaScript Assignment Operators
JavaScript Comparison Operators
JavaScript String Addition
Example
Note
Adding Strings and Numbers
JavaScript Logical Operators
JavaScript Bitwise Operators
Bitwise logical operators
JavaScript Bitwise AND
Example
JavaScript Bitwise OR
Example:
JavaScript Bitwise XOR
JavaScript Bitwise NOT (~)
JavaScript (Zero Fill) Bitwise Left Shift (<<)
JavaScript (Sign Preserving) Bitwise Right Shift (>>)
JavaScript (Zero Fill) Right Shift (>>>)
Converting Decimal to Binary
Converting Binary to Decimal
Chapter Six
JavaScript Data Types
JavaScript primitive data types
JavaScript non-primitive data types
Examples
The Concept of Data Types
JavaScript Types are Dynamic
JavaScript Strings
JavaScript String Methods
JavaScript String Length
Extracting String Parts
JavaScript String slice()
Note
Examples
JavaScript String substring()
Replacing String Content
Note
JavaScript String ReplaceAll()
Converting to Upper and Lower Case
JavaScript String concat()
JavaScript String trim()
JavaScript Numbers
JavaScript Random
Exponential Notation
JavaScript BigInt
JavaScript Integer Accuracy
How to Create a BigInt
JavaScript Booleans
The Boolean() Function
</html>
NaN data type
Comparisons and Conditions
JavaScript Comparison and Logical Operators
Comparison Operators
How Can it be Used
Conditional (Ternary) Operator
Syntax
Comparing Different Types
JavaScript if, else, and else if
Conditional Statements
The if Statement
Syntax
Example
The else Statement
Example
The else if Statement
Syntax
Example
JavaScript Switch Statement
Syntax
Example
The break Keyword
The default Keyword
JavaScript Arrays
JavaScript Array
JavaScript Array Methods
JavaScript Objects
The type of Operator
Chapter Seven
JavaScript Functions
Function Syntax
Function declarations
Function Invocation
Invoking a JavaScript Function
Note
The Term “This” in Javascript
Note
The Global Object
Invoking a Function as a Method
Invoking a Function with a Function Constructor
Function Return
The ( ) Operator
Functions Used as Variable Values
Local Variables
Chapter Eight
JavaScript Objects
Real Life Objects, Properties, and Methods
Object Properties
Accessing Object Properties
Object Methods
Example
The this Keyword
Accessing Object Methods
Do Not Declare Strings, Numbers, and Booleans as Objects!
Chapter Nine
JavaScript Events
HTML Events
Mouse events:
onclick Event Type
onsubmit Event Type
onmouseover and onmouseout
Keyboard events:
Form events:
Window/Document events
HTML DOM Events
Examples
JavaScript Event Handlers
––––––––
Chapter Ten
JavaScript Loop
Instead of writing:
You can write:
The For Loop
Flow chart
do...while statement
Example:
Differences between do... while and While Loop
While Statement
Example:
Comparison between the while and for loop:
for.......in Loop
Example: JavaScript For In Loop
Example Explained
for-in Loop Examples
Supported Browsers:
The For Of Loop
Explanation:
Explanation:
Explanation:
Chapter Eleven
Utilizing the JavaScript DOM
Properties of document object
Methods of document object
Accessing field value by document object
JavaScript - document.getElementById() method
JavaScript - document.getElementsByName() method
JavaScript - document.getElementsByTagName() method
Another example of document.getElementsByTagName() method
JavaScript - innerHTML
Example of innerHTML property
Show/Hide Comment Form Example using innerHTML
JavaScript - innerText
JavaScript innerText Example
Chapter Twelve
Javascript Browser Object Model
Understanding the Browser Environment
The user interface
Loader
HTML parsing
CSS parsing
JavaScript parsing
Layout and rendering
Igniting the BOM
The Navigator Object
Window Object
Methods of window object
Example of alert() in javascript
Example of confirm() in javascript
Example of prompt() in javascript
Example of open() in javascript
Example of setTimeout() in javascript
JavaScript History Object
Property of JavaScript history object
Methods of JavaScript history object
Example of history object
JavaScript Navigator Object
Property of JavaScript navigator object
Methods of JavaScript navigator object
Example of navigator object
JavaScript Screen Object
Property of JavaScript Screen Object
Example of JavaScript Screen Object
Chapter Thirteen
JavaScript Form Validation
Approach for Form Validation in JavaScript
JavaScript Form Validation Example
JavaScript Retype Password Validation
JavaScript Number Validation
JavaScript validation with image
JavaScript email validation
Chapter Fourteen
JavaScript Object Oriented Programming
JavaScript Classes
Class Declarations
Class Declarations Example
Class Declarations Example: Hoisting
Class Declarations Example: Re-declaring Class
Class expressions
Unnamed Class Expression
Class Expression Example: Re-declaring Class
Named Class Expression Example
JavaScript Objects
Creating Objects in JavaScript
1) JavaScript Object by object literal
2) By creating instance of Object
3) By using an Object constructor
Defining method in JavaScript Object
JavaScript Object Methods
JavaScript Prototype Object
Syntax:
Prototype Chaining
JavaScript Prototype Object
JavaScript Constructor Method
Points to remember
Constructor Method Example
JavaScript static Method
JavaScript static Method Example
Example 4
JavaScript Encapsulation
JavaScript Encapsulation Example
JavaScript Encapsulation Example: Validate
JavaScript Encapsulation Example: Prototype-based approach
JavaScript Inheritance
JavaScript extends Example: inbuilt object
JavaScript extends Example: Custom class
JavaScript extends Example: a Prototype-based approach
JavaScript Polymorphism
JavaScript Abstraction
Chapter Fifteen
JavaScript Cookies
How Cookies Works?
How to create a Cookie in JavaScript?
JavaScript Cookie Example
Cookie Attributes
Cookie expires attribute
Cookie max-age attribute
Cookie path attribute
Cookie path attribute Example
Cookie domain attribute
Cookie with multiple Name-Value pairs
Examples to Store Name-Value pair in a Cookie
Deleting a Cookie in JavaScript
Examples to delete a Cookie
Example 3
Chapter Sixteen
Integrating JavaScript with Google Apps Script
What can Apps Script do?
Custom Menus in Google Workspace
Clickable images and drawings in Google Sheets
Dialogs and Sidebars in Google Workspace Documents.
Alert dialogs
Prompt dialogs
Custom dialogs
Custom sidebars
File-open dialogs
Custom Functions in Google Sheets
Developing a custom function
obtaining a personalized feature via the Google Workspace Marketplace
Using a custom function
Guidelines for custom functions
Naming
Arguments
Return values
Data types
Autocomplete
Using Google Apps Script services
Sharing
Optimization
Google Sheets Macros
Creating macros in Apps Script
Editing macros
Importing functions as macros
Manifest structure for macros
Best practices
Things you can't do
Chapter Seventeen
Developing Web Apps in Apps Script
Requirements for web apps
Request parameters
Deploy a script as a web app
Test a web app deployment
Permissions
Embed your web app in Google Sites or any Site of your Choice.
Web Apps and Browser History
How to create Login and Register Form using Google spreadsheet data
How to Display Google Sheet Data on Webpage
How to Submit HTML Form Data to Google Spreadsheet
How to Submit HTML Form to Gmail
How to Search Google Sheet Contents from HTML Website.
Conclusion
JavaScript Introduction
Many websites utilize JavaScript (js), a lightweight object-oriented programming language, to script their webpages. When applied to an HTML document, this fully functional programming language that is interpreted allows for dynamic website interaction.
In 1995, JavaScript was released, allowing users of the Netscape Navigator browser to add applications to web pages. Since then, all other major graphical web browsers have implemented the language. It has enabled the development of contemporary online applications, which allow for immediate user interaction without requiring a page reload. Conventional websites also employ JavaScript to provide a variety of innovative features and interactive elements (Netscape, 2007).
Brendan Eich wrote JavaScript in ten days in May 1995. Eich was employed by Netscape, where he developed JavaScript for Netscape Navigator, the company's web browser. The plan was to use Java to create the main interactive components of the client-side web. JavaScript was intended to serve as the connecting language between those elements and to provide a little bit of interactivity to HTML. JavaScript needed to look like Java because of its supporting function in Java. That eliminated working options like TCL, Python, Perl, and others (W3C, 2021).
JavaScript is a language that improves the Web. The language can assist in transforming a static page of text into an intelligent, dynamic, and engaging experience when used on the client computer. JavaScript applications can be as subtle as greeting a visitor to a website with "Good morning!" when it is morning in the client computer's time zone. Other apps may be considerably more straightforward, like one that downloads a slide show's content in one page and uses JavaScript to manage the presentation's hiding, showing, and "flying slide" transitions.
JavaScript was first known as Mocha. When Netscape Navigator was first released in beta, it was called LiveScript. When Netscape 2 was released in 1995, it was renamed JavaScript. To avoid trademark difficulties, Microsoft swiftly reverse-engineered JavaScript and launched an exact clone of it in Internet Explorer, which they called Jscript.
JavaScript was accepted and standardized as EMCAScript in 1997 after Netscape submitted it to Ecma International, a standards body. Nevertheless, JavaScript and Java are unrelated programming languages. During the period when Java was becoming more and more prominent in the market, the name was offered and suggested. Databases like CouchDB and MongoDB use JavaScript as their scripting and query language in addition to web browsers. JavaScript founder Brandon Eich is well-known for his remarks against the standardized language's name, referring to ECMAScript (Ecma International) as a "unwanted trade name that sounds like a skin disease."
Not only is ECMAScript a terrible moniker for a programming language, but it's also the name that Netscape gave the language and that most people use to refer to it. If you are familiar with programming in Java or would like to learn at some time, it is a good idea to remember that although there are some similarities between the two languages, they are very different things. When JavaScript first came out, it was widely used to add dynamic elements to websites.
An early outcome of JavaScript being integrated into web browsers was the creation of so-called Dynamic HTML (DHTML), which allowed for a variety of entertaining effects, such as the falling snowflake effect, pop-up windows, and curling web page corners, as well as more practical features like drop-down menus and form validation.
The following are features of JavaScript:
All popular web browsers support JavaScript as they provide built-in execution environments.
JavaScript follows the syntax and structure of the C programming language. Thus, it is a structured programming language.
JavaScript is a weakly typed language, where certain types are implicitly cast (depending on the operation).
JavaScript is an object-oriented programming language that uses prototypes rather than using classes for inheritance.
It is a light-weighted and interpreted language.
It is a case-sensitive language.
JavaScript is supportable in several operating systems including, Windows, macOS, etc.
It provides good control to the users over the web browsers.
JavaScript is a programming language that enables the implementation of intricate features on websites. You can be sure that JavaScript is used whenever a website performs any function other than merely displaying static content for you to view. Examples of such functions include interactive maps, scrolling video jukeboxes, animated 2D/3D graphics, and timely content updates. It is the third layer in the stack of common web technologies, the first two of which (CSS and HTML) we have already thoroughly discussed in other Learning Area sections.
Many websites utilize JavaScript, a lightweight object-oriented programming language, to script their webpages. It is a complete programming language that is interpreted. When JavaScript is added to an HTML page, websites may have dynamic interactivity.
JavaScript enables users to create interactive contemporary web apps without constantly refreshing the page. JavaScript is frequently used with the DOM API to refresh a user interface by dynamically modifying HTML and CSS.
It is mostly employed in online programs. Let's talk about JavaScript's applications. An example of how JavaScript is used is seen in the image below.
Because browsers are getting better every day, JavaScript has become more and more popular as a tool for creating reliable online applications. We may comprehend it by using Google Maps as an example. With Maps, all a user needs to do is click and drag the mouse to view the information. These ideas are supported by the usage of JavaScript.
Creating web pages is a typical usage for JavaScript. It enables us to add special effects and dynamic behavior to the webpage. It is mostly used for validation on websites. JavaScript facilitates the execution of intricate tasks and allows websites to communicate with their users. Another way to load material into a document without refreshing the webpage is by using JavaScript.
Nowadays, a lot of people utilize their mobile devices to access the internet. We can also create an application for non-web environments using JavaScript. JavaScript is a fantastic technology for developing mobile applications because of its capabilities and applications. The popular JavaScript framework for making mobile apps is called React Native. We can create mobile applications for several operating systems with React Native. Writing separate code for the iOS and Android operating systems is not necessary. It simply has to be written once, and it can operate on several systems.
Games may also be made with JavaScript. It offers a number of frameworks and libraries for making games. Either a 2D or 3D game may be played. A few JavaScript game engines like Pixi.js and PhysicsJS assist us in making an online game. Additionally, we may render 2D and 3D pictures on browsers by using the JavaScript API known as the WebGL (web graphics library).
Moreover, JavaScript facilitates the creation of websites and presentations. You may utilize the libraries, such BespokeJs and RevealJs, to make an online slide show. Because they are simpler to utilize, we can quickly and simply create something incredible.
With the use of HTML, Reveal.js is used to build stunning and dynamic slide decks. Tablets and mobile devices are ideal for these presentations. All CSS color formats are also supported. Animated bullet lists, responsive scaling, and an extensive feature set are all included in the BespokeJS.
Many web applications feature a server-side component. HTTP requests are handled and content is generated using JavaScript. Node.js allows JavaScript to operate on servers as well. The environment that Node.js offers has all the tools needed for JavaScript to execute on servers.
Node.js may be used to develop a web server. Because Node.js is event-driven, it doesn't wait for the preceding call's answer. Node.js servers carry large amounts of data quickly and without the need for buffering. The createServer() function in the HTTP module may be used to create the server. Whenever someone attempts to access port 8080, this function gets called. The HTTP server should show HTML in response, and it should also be provided in the HTTP header.
Websites that are interactive are made with JavaScript. There are several other applications for JavaScript that aid in enhancing webpage speed. The following is a list of other uses for JavaScript:
Client-side validation.
Dynamic drop-down menus,
Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box and prompt dialog box),
Displaying clocks
Displaying date and time.
To validate the user input before submission of the form.
Open and close new windows.
To display dialog boxes and pop-up windows.
To change the appearance of HTML documents.
To create the forms that respond to user input without accessing the server.
Before starting to build your first JavaScript application, make sure you have all of your tools assembled and ready. By coincidence, the tools we use in this book are also the ones we recommend you download and install. We lead you through the procedure. Please feel free to utilize any comparable or preferred tools you may have.
To understand why we selected these tools and to help you decide whether or not to use them, we still advise you to read this portion of the book. We provide you with some pointers on how to maximize the functionality of each tool when you install it.
Downloading and installing Chrome
Google Chrome is the preferred web browser for dealing with JavaScript. It's acceptable, of course, if you would rather use a different web browser on a daily basis. Every browser will execute JavaScript accurately and quickly. But since Google Chrome will be covered in some detail in this book, we advise you to at least install it on your computer using the steps outlined in this chapter. Because Google Chrome is now the most popular web browser on the Internet and provides great features for making JavaScript writers' tasks simpler, we decided to utilize it in this book. (Yes, its popularity surpasses that of Internet Explorer.)
If you don’t have Chrome installed, follow these steps to install it:
Go to www.google.com/chrome.
Hover over the Download tab and choose the appropriate version for your computer.
Open the downloaded file and follow the instructions to install Chrome
Google Chrome parses, compiles, and executes JavaScript code using Google's V8 JavaScript engine. Chrome is either the fastest or among the fastest browsers at running JavaScript, depending on whose benchmarking test you trust. The main browser manufacturers are always trying to surpass one another. The competition has accelerated the pace of every browser's JavaScript engine in recent years, so it doesn't really matter who is the quickest at any one moment. You may visit http://arewefastyet.com to view real-time comparisons of the performance of several browsers in JavaScript tests.
The most popular browsers' JavaScript performance is automatically checked and graphed on this site, which is updated many times a day by Mozilla, the company that created the Firefox browser.
Downloading and installing a code editor
A source code editor, sometimes called a code editor, is essentially a text editor with extra features that make it easier to create and modify computer code. Sublime Text is the one we use. There are several code editors available, so feel free to pick your preferred one if you already know how to use it and find it comfortable. Code editors are very individualized tools, and many programmers will discover that they work better with a particular one solely because it seems more natural to them. If you discover that Sublime Text simply isn't your thing.
Name
Location
Compatible with
Coda
http://panic.com/coda
Mac only
Aptana
www.aptana.com
Mac or Windows
Komodo Edit
www.activestate.com/komodo‐edit/downloads
Mac or Windows
Dreamweaver
http://adobe.com/products/dreamweaver.html
Mac or Windows
Eclipse
www.eclipse.org
Mac or Windows
Notepad++
http://notepad‐plus‐plus.org
Windows only
TextMate
http://macromates.com
Mac only
BBEdit
www.barebones.com/products/bbedit
Mac only
EMacs
www.gnu.org/software/emacs
Mac or Windows
TextPad
www.textpad.com
Windows only
vim
www.vim.org
Mac or Windows
Netbeans
https://netbeans.org
Mac or Windows
Bracket
https://brackets.io/
Mac or Windows
Visual Studio Code
https://code.visualstudio.com/
Mac or Windows
Reading JavaScript Code
Before you get started with writing JavaScript programs, you need to be aware of a few rules of JavaScript:
JavaScript is case-sensitive. We repeat this several times throughout the book, because it’s an error that those who are new to JavaScript make quite frequently. To JavaScript, the words pants and Pants are completely different.
JavaScript doesn’t care much about white space. White space includes spaces, tabs, and line breaks — any character that doesn’t have a visual representation. When you’re writing JavaScript code, it doesn’t matter if you use one space, two spaces, a tab, or even a line break (in most cases) within the code. JavaScript will ignore white space. The one exception is when you’re writing out text that you want JavaScript to print to the screen. In this case, the white space you use will show up in the end result. The best practice, with regards to white space in your code, is to use enough space that your code is easy to read and to also be consistent with how you use this space.
Watch out for reserved words. JavaScript has a list of words that have special meaning to the language. We list these words in Chapter 3. For now, just be aware that some words, such as function, while, break, and with have special meanings.
JavaScript likes semicolons: JavaScript code is made up of statements. You can think of statements as similar to sentences. They are fundamental building blocks for JavaScript programs in the same way that sentences are the building blocks of paragraphs. In JavaScript, statements end with a semicolon. If you don’t use a semicolon at the end of a statement, JavaScript will put it there for you. This can lead to unexpected results, however, so it’s considered a best practice to always end statements with a semicolon.
While JavaScript is used in many other contexts, web browsers are the most popular location to observe it in the wild. JavaScript was created to handle typical browser actions like clicks and scrolling, control inputs and outputs, manipulate online pages, and control the many functionalities of web browsers!
To run JavaScript in a web browser, you have three options, all of which will be shown in the following pages:
Put it directly in an HTML event attribute
Put it between an opening and closing script tag
Put it in a separate document and include it in your HTML document
Many times, you’ll use a combination of all three techniques within any one web page. However, knowing when to use each is important and is a skill that you’ll learn with more practice.
HTML has a number of unique properties that are intended to cause JavaScript to run in response to events that occur in the web browser or user actions. An HTML button with an event property that reacts to mouse click events is seen here:
<button id="bigButton" onclick="alert('Hello World!');">Click Here</button>
In this case, when a user clicks on the button created by this HTML element, a popup will appear with the words “Hello World!”. HTML has over 70 different event attributes. Table 2-3 shows the most commonly used ones.
Commonly Used HTML Event Attributes
Attribute
Description
onload
Runs the script after the pages finishes loading
onfocus
Runs the script when the element gets focus (such as when a text box is active)
onblur
Runs the script when the element loses focus (such as when the user clicks a new text box in a form)
onchange
Runs the script when the value of an element is changed
onselect
Runs the script when text has been submitted
onsubmit
Runs the script when a form has been submitted
onkeydown
Runs the script when a user is pressing a key
onkeypress
Runs the script when a user presses a key
onkeyup
Runs the script when a user releases a key
onclick
Runs the script when a user mouse clicks an element
ondrag
Runs the script when an element is dragged
ondrop
Runs the script when a dragged element is being dropped
onmouseover
Runs the script when a user moves a mouse pointer over an element
The HTML script element allows you to embed JavaScript into an HTML document. Often script elements are placed within the head element, and, in fact, this placement was often stated as a requirement. Today, however, script elements are used within the head element as well as in the body of web pages. The format of the script element is very simple:
<script>
(insert your JavaScript here)
</script>
In this case, however, we place the script element at the bottom of the body element
Scripts are generally loaded by web browsers and run when they load. The browser reads a web page from top to bottom, exactly like it would read a text page. Occasionally, you should wait for the script to execute until the browser has finished loading the page's contents. We used the body element's onload event property to do this. Placing the code that has to be run at the conclusion of the code is another popular technique to postpone execution.
Limitations of JavaScript in <script> elements
Although embedding JavaScript into a script element is far more popular and widely accepted than inline scripting (placing JavaScript into event attributes), it still has some significant drawbacks. The main drawback is that these kinds of scripts are only usable on the web page on which they are placed. To put it another way, if you include JavaScript in a script element, you must duplicate and paste the script element precisely onto each page that has it. You can understand how this may turn into a maintenance nightmare given that some websites have hundreds or even thousands of web pages.
When to use JavaScript in <script> elements
There are applications for this JavaScript embedding technique. It is okay and can even speed up the loading and display of your web pages by reducing the number of requests the web server needs to make to the server for those JavaScript elements that do nothing more than call other JavaScript elements.
As the name suggests, single-page applications only have one HTML page, making them excellent candidates for this kind of embedding as there is only one location where the script has to be updated. Generally speaking, though, you want to try to avoid adding too much JavaScript straight into an HTML page. Your code will become more organized and require less maintenance as a consequence.
Including external JavaScript files
The src property of the script element is the third and most often used method of including JavaScript in HTML texts. The only difference between a script element with JavaScript between the tags and one with a src attribute is that the JavaScript is loaded into the HTML document from a different file.
External scripts are practical when the same code is used in many different web pages.
JavaScript files have the file extension .js.
To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:
Here’s an example of a script element with a src attribute:
<script src="myScript.js"></script>
In this case, you would have a separate file, named myScript.js, that would reside in the same folder as your HTML document.
<!DOCTYPE html>
<html>
<body>
<h2>Demo External JavaScript</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p>This example links to "myScript.js".</p>
<p>(myFunction is stored in "myScript.js")</p>
<script src="myScript.js"></script>
</body>
</html>
NB:
i. You can place an external script reference in <head> or <body> as you like.
ii. The script will behave as if it was located exactly where the <script> tag is located.
iii. External scripts cannot contain <script> tags.
The benefits of using external JavaScript files are that using them
Keeps your HTML files neater and less cluttered
Makes your life easier because you need to modify JavaScript in only one place when something changes or when you make a bug fix
It separates HTML and code
It makes HTML and JavaScript easier to read and maintain
Cached JavaScript files can speed up page loads
To add several script files to one page - use several script tags:
<script src="myScript1.js"></script>
<script src="myScript2.js"></script>
Creating an external JavaScript file is similar to creating an HTML file or another other type of file. To create an external JavaScript file, follow these steps:
In Sublime Text or any of your text editor, choose File ➪ New File.
Copy everything between <script> and </script> from MyFirstProgram.html and paste it into your new .js file.
NB: Notice that external JavaScript files don’t contain <script> elements, just the JavaScript.
Save your new file as countToTwenty.js in the same folder as MyFirstProgram.html.
In MyFirstProgram.html, modify your script element to add a src attribute, like this:
An external script can be referenced in 3 different ways:
With a full URL (a full web address)
With a file path (like /js/)
Without any path
Example 1: This example uses a full URL to link to myScript.js:
<!DOCTYPE html>
<html>
<body>
<h2>External JavaScript</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Click Me</button>
<p>This example uses a full web URL to link to "myScript.js".</p>
<p>(myFunction is stored in "myScript.js")</p>
<script src="https://www.w3schools.com/js/myScript.js"></script>
</body>
</html>
Example 2: This example uses a file path to link to myScript.js:
<!DOCTYPE html>
<html>
<body>
<h2>External JavaScript</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p>This example uses a file path to link to "myScript.js".</p>
<p>(myFunction is stored in "myScript.js")</p>
<script src="/js/myScript.js"></script>
</body>
</html>
Example 3: This example uses no path to link to myScript.js:
<!DOCTYPE html>
<html>
<body>
<h2>Demo External JavaScript</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p>This example links to "myScript.js".</p>
<p>(myFunction is stored in "myScript.js")</p>
<script src="myScript.js"></script>
</body>
</html>
Using the JavaScript Developer Console
Sometimes, it’s helpful to be able to run JavaScript commands without creating an HTML page and including separate scripts or creating <script> blocks. For these times, you can use the Chrome browser’s JavaScript Console. To access the JavaScript Console, find the Chrome menu in the upper-right corner of your browser. It looks like three horizontal lines. Click the Chrome menu and then find More Tools in the drop-down menu. Under More Tools, choose JavaScript Console from the drop-down menu.
And, yes, there is a faster way to open the JavaScript Console. Simply press Alt+Command+J (on Mac) or Control+Shift+J (on Windows).
The JavaScript Console is perhaps the best friend of the JavaScript developer. Besides allowing you to test and run JavaScript code quickly and easily, it also is where errors in your code are reported, and it has features that will help you track down and solve problems with your code.
Once you’ve opened the JavaScript console, you can start inputting commands into it, which will run as soon as you press Enter. To try it out, open the JavaScript console and then type the following commands, pressing Enter after each one: