HTML Javascript
A script is a small program used with HTML to make web pages more attractive, dynamic, and interactive, such as an alert popup window on mouse click. Currently, the most popular scripting language used for websites is JavaScript.
The HTML <script> tag is used to specify a client-side script. It can be an internal or external JavaScript file that contains scripting statements, and it can be placed within the <body> or <head> section.
JavaScript is mainly used to manipulate images, perform form validation, and change content dynamically. To select an HTML element, JavaScript uses the document.getElementById() method.
Ways to add Javqascript
External JavaScript
External JavaScript is used when you need to define the functionality that will be used in multiple HTML documents. It is better to keep that functionality in a separate JavaScript file with a .js extension, and then include that file in your HTML documents using the <script> tag.
It is important to note that you should not add the <script> tag in the external file, and provide the complete path where you have put the JS file.
Additionally, there are other features related to scripting in HTML such as internal JavaScript, event handlers, the <noscript> element, and more.
External Script File (script.js)
function Hello() {
alert("Hello, Javascript World");
}
Output will be
Internal JavaScript
We can write your script code directly into your HTML document. Usually, we keep script code in the header of the document using <script> tag, otherwise, there is no restriction and you can put your source code anywhere in the document but inside <script> tag.
Event Handlers
An event is something which user does, or browser does such as mouse click or page loading are examples of events, and JavaScript comes in the role if we want something to happen on these events.
HTML provides event handler attributes which work with JavaScript code and can perform some action on an event.
HTML can have following events such as:
- Form events: reset, submit, etc.
- Select events: text field, text area, etc.
- Focus event: focus, blur, etc.
- Mouse events: select, mouse up, mouse move, mouse down, click, double click, etc.
List for Windows Event Attributes:
Event Name |
Handler Name |
Occurs When |
onBlur |
blur |
When form input loses focus |
onClick |
click |
When the user clicks on a form element or a link |
onSubmit |
submit |
When a user submits a form to the server. |
onLoad |
load |
When page loads in a browser. |
onFocus |
focus |
When a user focuses on an input field. |
onSelect |
select |
When a user selects the form input filed. |
Code Example
<input type="button" value="Click" onclick="alert('Hi, how are you')">
HTML noscript Element
HTML <noscript> tag is used to write disabled script in the browser. The text written within <noscript> </noscript> tag is not displayed on the browser.