Resources | Subject Notes | Information Technology IT
JavaScript is a powerful scripting language that enables dynamic and interactive content on web pages. It runs within the user's web browser, allowing developers to manipulate the Document Object Model (DOM), respond to user events, and communicate with servers.
JavaScript code is typically embedded within HTML using the tag. Basic syntax includes variables, data types, operators, and control flow statements.
Concept | Description | Example |
---|---|---|
Variables | Used to store data. | let name = "John"; |
Data Types | Types of data stored in variables (e.g., string, number, boolean). | let age = 30; (number), let isStudent = false; (boolean) |
Operators | Symbols that perform operations on values (e.g., +, -, *, /). | let result = 10 + 5; |
Control Flow | Statements that control the order in which code is executed (e.g., if , else , for ). |
|
The DOM provides a tree-like structure representation of the HTML document. JavaScript can interact with this structure using methods like getElementById
, querySelector
, and innerHTML
.
Example: Changing the text content of an element.
document.getElementById("myElement").innerHTML = "New Text";
Example: Adding a new element to the DOM.
let newElement = document.createElement("p");
newElement.textContent = "This is a new paragraph.";
document.body.appendChild(newElement);
JavaScript can be used to attach event listeners to HTML elements. These listeners trigger specific functions when certain events occur.
Example: Responding to a click event.
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});
Example: Handling a form submission.
document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault(); // Prevent the default form submission
// Process the form data here
});
AJAX allows JavaScript to fetch data from a server without reloading the entire page. This is useful for updating parts of the page dynamically.
Example: Fetching data using fetch
.
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log(data);
// Update the page with the fetched data
})
.catch(error => {
console.error('Error fetching data:', error);
});
This provides a foundational overview of using JavaScript for web interactivity. Further exploration involves learning about more advanced topics like frameworks (e.g., React, Angular, Vue.js), asynchronous programming, and data handling.