JavaScript is a programming language used to create dynamic content for websites. JavaScript brings a webpage to life by allowing users to interact with elements on the page, such as actions on clicking buttons, filling out forms, and showing animations.
First Program: “Hello, World!”
A “Hello, World!” program is the simplest way to get started with any programming language. Here’s how you can write one in JavaScript.
<html>
<head></head>
<body>
<h1>Check the console for the message!</h1>
<script>
// This is our first JavaScript program
console.log("Hello, World!");
</script>
</body>
</html>
The <script> tag is used to include JavaScript code inside an HTML document. console.log() prints messages to the browser’s developer console. Open the browser console to see the “Hello, World!” message.
To add JavaScript in HTML document, several methods can be used. These methods include embedding JavaScript directly within the HTML file or linking an external JavaScript file.
<!DOCTYPE html>
<html>
<head>
<title> Inline JavaScript </title>
</head>
<body>
<h2> Adding JavaScript in HTML Document</h2>
<button onclick="alert('Button Clicked!')"> Click Here </button>
</body>
</html>
Events
JavaScript Events are actions that happen in the browser, such as mouse clicks, keyboard input, or page loading. They can be triggered by various user interactions or by the browser itself.
<html>
<script>
function myFun() {
document.getElementById("newP").innerHTML = "New Text";
}
</script>
<body>
<button onclick="myFun()">Click me</button>
<p id="newP"> </p>
</body>
</html>
Event Types
JavaScript supports a variety of event types. Common categories include:
- Mouse Events: click, dblclick, mousemove, mouseover, mouseout
- Keyboard Events: keydown, keypress, keyup
- Form Events: submit, change, focus, blur
- Window Events: load, resize, scroll
These denote mouse actions like click,doubleclick,movement into an area ,keyboard actions etc, they trigger the respective actions defined on occurance. They also have their own set of properties like timestamp which can be used in programing real time applications