Dynamic HTML: DOM & JavaScript Basics
Dynamic HTML: DOM & JavaScript Basics
1. Structure Representation: The DOM provides a tree-like structure where each part
of a webpage (such as elements, attributes, and text) is represented as nodes. This
makes it possible to access and modify elements like HTML tags, attributes, and text
content.
2. Manipulation: Using JavaScript, the DOM allows you to:
o Add, remove, or modify elements (like <div>, <span>, etc.).
o Change styles (using inline CSS or through style properties).
o Handle events (like onclick, onmouseover).
3. Dynamic Content: The "dynamic" part of DHTML refers to the ability to change
content without reloading the entire page. With JavaScript and the DOM, you can
modify the webpage in real-time, making it interactive and responsive.
Example:
html
CopyEdit
<!DOCTYPE html>
<html>
<head>
<title>DHTML DOM Example</title>
<style>
#myText {
color: blue;
}
</style>
</head>
<body>
<h1>Welcome to DHTML!</h1>
<p id="myText">This text is blue.</p>
<button onclick="changeText()">Click me</button>
<script>
function changeText() {
var element = [Link]("myText");
The DOM allows the page to be altered in response to events like button clicks, making it a
core part of DHTML for creating interactive and dynamic web pages.
Attach
Search
Reason
Accessing HTML & CSS through DCOM Dynamic content styles & positioning
Dynamic content system that involves HTML and CSS, possibly related to dynamic content
or elements in a web application, and managing styles and positioning dynamically.
Dynamic content styles and positioning, there are several concepts and tools you might be
referring to. Below is an overview of how HTML and CSS work in dynamic content systems,
with focus on DCOM (Dynamic Component Object Model) if that's part of your scenario.
Dynamic content refers to content on a webpage that can change or update without the user
manually refreshing the page. This could include things like live updates, interactive forms,
or content that changes based on user input or data from the server.
2. Positioning in CSS:
CSS positioning allows you to control the layout of elements on a page dynamically. There
are several key positioning methods:
Static: The default positioning method. Elements are placed in the normal document
flow.
Relative: Elements are positioned relative to their normal position in the document
flow.
Absolute: Elements are positioned relative to their closest positioned ancestor or the
initial containing block.
Fixed: Elements are positioned relative to the viewport, so they stay in place even
when the page is scrolled.
Sticky: A hybrid of relative and fixed positioning. The element is treated as relative
until it crosses a specific point in the viewport, after which it becomes fixed.
DCOM is typically associated with Windows and is used for communication between
software components over a network. However, in the context of web development, it's likely
you're referring to dynamic components (like a CMS, JavaScript-driven components, or
dynamic front-end frameworks) rather than DCOM itself. If you're using JavaScript
frameworks (React, Vue, Angular) or libraries that allow dynamic content generation and
style changes, CSS properties such as display, position, and transform can be manipulated.
In frameworks like React, you may use inline styles with style={{}} or dynamic class names
to change styles based on the state of a component.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.dynamic-box {
width: 100px;
height: 100px;
background-color: blue;
position: absolute; /* This enables positioning */
top: 0;
left: 0;
transition: top 0.5s, left 0.5s; /* Smooth transition for position */
}
</style>
<title>Dynamic Positioning</title>
</head>
In this example:
Responsiveness: When dealing with dynamic content and positioning, ensure your
layout adapts to different screen sizes. This might involve using CSS media queries or
flexible layout systems like Flexbox or Grid.
Performance: Excessive DOM manipulations or complex animations may negatively
impact performance, especially for mobile users. Consider using
requestAnimationFrame for smoother animations or reducing layout reflows and
repaints.
Event bubbling is a concept in DHTML (Dynamic HTML) that describes how events
propagate through the DOM (Document Object Model) hierarchy. It refers to the order in
which events are handled by elements in the DOM when an event (such as a mouse click,
key press, etc.) occurs.
Example:
Imagine a webpage with nested HTML elements, such as a div containing a button:
<div id="parent">
<button id="child">Click me!</button>
</div>
If you attach event listeners to both the button (child) and the div (parent):
[Link]("child").addEventListener("click", function(event)
{
alert("Button clicked");
});
[Link]("parent").addEventListener("click", function(event)
{
alert("Div clicked");
});
If you want to prevent the event from reaching the parent elements, you can stop the event
from bubbling:
javascript
[Link]("child").addEventListener("click", function(event) {
alert("Button clicked");
[Link](); // Prevent the event from bubbling up
});
With [Link](), only the button's event listener is executed, and the parent div
won't receive the event.
Key Points:
Event Bubbling: The event starts at the target and propagates up the DOM.
[Link](): Stops the event from propagating to parent elements.
Use Case: Event delegation can be achieved using event bubbling, allowing you to
attach a single event listener to a parent element instead of multiple listeners on many
child elements.
Data binding
Data binding in DHTML (Dynamic HTML) refers to the concept of connecting data to
HTML elements dynamically, so that the content on the web page updates automatically
when the underlying data changes. In the context of DHTML, data binding involves
connecting JavaScript code with HTML elements (like text boxes, tables, etc.) so that the
DOM (Document Object Model) can reflect any changes in the data without needing to
refresh the page.
1. JavaScript and DOM Manipulation: You can manipulate the DOM using
JavaScript to bind data to elements on the page. When the data changes, JavaScript
will update the HTML elements.
2. Example of Simple Binding:
<!DOCTYPE html>
<html>
<head>
<title>Data Binding Example</title>
</head>
<body>
<div>
<p>Name: <span id="userName"></span></p>
<button onclick="updateName()">Change Name</button>
</div>
<script>
let user = { name: 'John Doe' };
In this example:
o The bindData() function is responsible for updating the content of the span
element (#userName) with the value from the JavaScript [Link].
o The updateName() function changes the [Link] and then calls bindData()
again to update the page.
A more complex concept would be two-way data binding, where changes to the HTML
elements reflect in the data model and vice versa. For this, you often need more advanced
JavaScript code or frameworks. One simple example using plain JavaScript could be using
event listeners:
<!DOCTYPE html>
<html>
<head>
<title>Two-Way Data Binding Example</title>
</head>
<script>
let user = { name: '' };
In this case:
There are also many JavaScript libraries and frameworks that offer more advanced data
binding capabilities, such as:
While these modern frameworks make data binding easier and more powerful, you can still
implement basic data binding in pure JavaScript like the examples above.
JavaScript is a versatile, dynamically typed programming language used for interactive web
applications, supporting both client-side and server-side development, and integrating
seamlessly with HTML, CSS, and a rich standard library.
JavaScript is a single-threaded language that executes one task at a time.
It is an Interpreted language which means it executes the code line by line.
The data type of the variable is decided at run-time in JavaScript that’s why it is
called dynamically typed.
“Hello, World!” Program in Browser Console
A “Hello, World!” program is the simplest way to get started with any programming
language. Here’s how you can write one using JavaScript.
<html>
<head></head>
<body>
<h1>Check the console for the message!</h1>
<script>
// This is our first JavaScript program
[Link]("Hello, World!");
</script>
</body>
</html>
In this example
The<script> tag is used to include JavaScript code inside an HTML document.
[Link]() prints messages to the browser’s developer console. Open the browser
console to see the “Hello, World!” message.
“Hello World” Program in Server Console
We can also print the “Hello World” program directly into the console terminal without
embedded it into HTML. Create an [Link] file and add the code to it.
/*
This is a multi-line comment.
It can span several lines.
*/
[Link]("Hello, World!"); // Prints Hello, World! to the console
Developing JavaScript involves writing and running code that adds interactivity and
functionality to web pages. Here's a step-by-step guide to help you get started with JavaScript
development:
A Text Editor: You can use any text editor to write JavaScript. Popular options
include:
o VSCode (Visual Studio Code): Highly recommended for web development
with great extensions for JavaScript.
o Sublime Text: A lightweight editor with JavaScript syntax support.
o Atom: A customizable open-source editor.
o Notepad++: A simple text editor for Windows users.
Web Browser: You'll need a browser to run and test your JavaScript. Most modern
browsers (Chrome, Firefox, Edge) have built-in developer tools to help debug
JavaScript code.
Variables
Global Variables
Global variables in JavaScript are those declared outside of any function or block scope.
They are accessible from anywhere within the script, including inside functions and blocks.
Variables declared without the var, let, or const keywords (prior to ES6) inside a function
automatically become global variables.
Local Variables
Local variables are defined within functions in JavaScript. They are confined to the scope
of the function that defines them and cannot be accessed from outside. Attempting to access
local variables outside their defining function results in an error.
Characteristics of Local Variables:
Scope: Limited to the function or block in which they are declared.
Function-Specific: Each function can have its own local variables, even if they share
the same name
Variables
A variable is like a container that holds data that can be reused or updated later in the
program. In JavaScript, variables are declared using the keywords var, let, or const.
1. var Keyword
The var keyword is used to declare a variable. It has a function-scoped or globally-scoped
behaviour.
Example
var n = 5;
[Link](n);
var n = 20; // reassigning is allowed
[Link](n);
output
5
20
2. let Keyword
The let keyword is introduced in ES6, has block scope and cannot be re-declared in the
same scope.
Example
let n= 10;
Output
20
3. const Keyword
The const keyword declares variables that cannot be reassigned. It’s block-scoped as well.
Example
const n = 100;
// n = 200; This will throw an error
[Link](n)
Output
100
Data Types
JavaScript supports various datatypes, which can be broadly categorized into primitive and
non-primitive types.
Primitive Datatypes
Primitive datatypes represent single values and are immutable.
1. Number: Represents numeric values (integers and decimals).
let n = 42;
let pi = 3.14;
2. String: Represents text enclosed in single or double quotes.
let s = "Hello, World!";
3. Boolean: Represents a logical value (true or false).
let bool= true;
[Link]: A variable that has been declared but not assigned a value.
Example
let notAssigned;
[Link](notAssigned);
output
undefined
Functions in JavaScript
Functions in JavaScript are reusable blocks of code designed to perform specific tasks.
They allow you to organize, reuse, and modularize code. It can take inputs, perform actions,
and return outputs.
Function Definition
A Function Definition or function statement starts with the function keyword and
continues with the following.
Function’s name.
A list of function arguments contained in parenthesis and separated by commas.
Statements are enclosed in curly brackets.
Syntax:
function name(arguments)
{
javascript statements
}
Example
function sum(x, y) {
return x + y;
}
[Link](sum(6, 9));
Output
15
Function Syntax and Working
A function definition is sometimes also termed a function declaration or function statement.
Below are the rules for creating a function in JavaScript:
Output
Hello User welcome to GeeksforGeeks
Why Functions?
Functions can be used multiple times, reducing redundancy.
Break down complex problems into manageable pieces.
Manage complexity by hiding implementation details.
Can call themselves to solve problems recursively.
Function Invocation
The function code you have written will be executed whenever it is called.
Triggered by an event (e.g., a button click by a user).
When explicitly called from JavaScript code.
Automatically executed, such as in self-invoking functions.
Function Expression
It is similar to a function declaration without the function name. Function expressions can be
stored in a variable assignment.
Syntax:
let geeksforGeeks= function(paramA, paramB) {
// Set of statements
}
Example:
const mul = function (x, y) {
Output
20
Arrow Functions
Arrow functions are a concise syntax for writing functions, introduced in ES6, and they do
not bind their own this context.
Syntax:
let function_name = (argument1, argument2 ,..) => expression
Example:
const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];
Output
Normal way [ 8, 6, 7, 9 ]
Using Arrow Function [ 8, 6, 7, 9 ]
Immediately Invoked Function Expression (IIFE)
IIFE functions are executed immediately after their definition. They are often used to create
isolated scopes.
(function () {
})();
Output
This runs immediately!
Callback Functions
A callback function is passed as an argument to another function and is executed after the
completion of that function.
Example
function num(n, callback) {
return callback(n);
}
[Link](num(5, double));
Output
10
Anonymous Functions
Anonymous functions are functions without a name. They are often used as arguments to
other functions.
setTimeout(function () {
[Link]("Anonymous function executed!");
}, 1000);
function outerFun(a) {
function innerFun(b) {
return a + b;
}
return innerFun;
}
Output
15
Pure Functions
Pure functions return the same output for the same inputs and do not produce side effects.
They do not modify state outside their scope, such as modifying global variables, changing
the state of objects passed as arguments, or performing I/O operations.
function pureAdd(a, b) {
return a + b;
}
[Link](pureAdd(2, 3));
Output
5
Characteristics of Functions
Parameters and Arguments: Functions can accept parameters (placeholders) and be
called with arguments (values).
Return Values: Functions can return a value using the return keyword.
Default Parameters: Default values can be assigned to function parameters.
Advantages of Functions in JavaScript
Reusability: Write code once and use it multiple times.
Loops in JavaScript are used to reduce repetitive tasks by repeatedly executing a block of
code as long as a specified condition is true. This makes code more concise and efficient.
Suppose we want to print ‘Hello World’ five times. Instead of manually writing the print
statement repeatedly, we can use a loop to automate the task and execute it based on the
given condition.
Types
1)for loop when the number of iterations is known.
2)while loop when the condition depends on dynamic factors.
3)do-while loop to ensure the block executes at least once.
4)for…in loop to iterate over object properties.
5)for…of loop for iterating through iterable objects.
Output
Count: 1
Count: 2
Count: 3
In this example
Initializes the counter variable (let i = 1).
Tests the condition (i <= 3); runs while true.
Executes the loop body and increments the counter (i++).
2. JavaScript while Loop
The while loop executes as long as the condition is true. It can be thought of as a repeating
if statement.
Syntax
while(condition)
{
//Codetoexecute
}
let i = 0;
while (i < 3) {
[Link]("Number:", i);
i++;
}
Output
Number: 0
Number: 1
Number: 2
In this example
Initializes the variable (let i = 0).
Runs the loop body while the condition (i < 3) is true.
Increments the counter after each iteration (i++).
3. JavaScript do-while Loop
The do-while loop is similar to while loop except it executes the code block at least once
before checking the condition.
Syntax
do
{
//Codetoexecute
} while (condition);
Example
let i = 0;
do {
[Link]("Iteration:", i);
i++;
} while (i < 3);
Output
name : Ashish
age : 25
In this example:
Iterates over the keys of the person object.
Accesses both keys and values.
5. JavaScript for-of Loop
The for…of loop is used to iterate over iterable objects like arrays, strings, or sets. It
directly iterate the value and has more concise syntax than for loop.
Syntax
for(letvalueofiterable)
{
//Codetoexecute
}
Example:
let a = [1, 2, 3, 4, 5];
for (let val of a) {
[Link](val);
}
Output
1
2
3
Conditional Statements
JavaScript have the following conditional statements:
i)The if Statement
Use the if statement to specify a block of JavaScript code to be executed if a condition is true.
The if statement is used to evaluate a particular condition. If the condition holds true, the
associated code block is executed.
Syntax
if (condition)
{
// block of code to be executed if the condition is true
}
Example
<script>
let i = 10;
if (i > 15) [Link]("10 is less than 15");
// This statement will be executed
// as if considers one statement by default
[Link]("I am Not in if");
</script>
Output
I am Not in if
The if else Statement
Use the else statement to specify a block of code to be executed if the condition is false.
The if-else statement will perform some action for a specific condition. Here we are using
the else statement in which the else statement is written after the if statement and it has no
condition in their code block .
if (i < 15)
[Link]("i is less than 15");
else
[Link]("I am Not in if");
</script>
Output
i is less than 15
The JavaScript Switch Statement
Use the switch statement to select one of many code blocks to be executed.
As the number of conditions increases, you can use multiple else-if statements in
JavaScript. but when we dealing with many conditions, the switch statement may be a more
preferred option.
Syntax
switch(expression)
{
case x:
//codeblock
break;
case y:
//codeblock
break;
default:
// codeblock
}
Switch Statement Example: Here, we will print the day name on day 3.
Example:
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
Output
Wednesday
Explanation:
Day is set to 3.
The switch statement evaluates day.
Since day is 3, the case 3 the block is executed, assigning "Wednesday" to dayName.
The break statement ends the switch statement, preventing execution from continuing
into other cases.
continue statement
continue statement in JavaScript is used to break the iteration of the loop and follow with
the next iteration.
Example of continue to print only odd Numbers smaller than 10
for (let i = 0; i < 10; i++) {
Output
15