0% found this document useful (0 votes)
3 views8 pages

JavaScript Day2 Functions Events

The document covers basic concepts of JavaScript functions, including their definition, usage with parameters, and return values. It also explains event handlers and provides examples of DOM events and interactivity through changing text and toggling colors. Overall, it serves as an introductory guide to creating interactive web elements using JavaScript.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views8 pages

JavaScript Day2 Functions Events

The document covers basic concepts of JavaScript functions, including their definition, usage with parameters, and return values. It also explains event handlers and provides examples of DOM events and interactivity through changing text and toggling colors. Overall, it serves as an introductory guide to creating interactive web elements using JavaScript.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaScript - Day 2

Functions, Event Handlers, Basic


Interactivity
What are Functions?

• Block of reusable code


• Used to perform a task
• Improves code readability and reuse
Example:
function greet() {
alert("Hello!");
}
Function with Parameters

Example:
function greet(name) {
alert("Hello " + name);
}

greet("Rehan");
Return Values

Example:
function add(a, b) {
return a + b;
}

let result = add(3, 4); // result = 7


Event Handlers

• Common events: onclick, onmouseover, onchange

Example:
<button onclick="sayHello()">Click Me</button>

<script>
function sayHello() {
alert("Hi there!");
}
</script>
DOM Events
Example:
<p onmouseover="highlight(this)" onmouseout="unhighlight(this)">Hover
me!</p>

<script>
function highlight(element) {
element.style.color = "red";
}

function unhighlight(element) {
element.style.color = "black";
}
</script>
Interactivity Example 1

Change Text Example:


<p id="text">Hello</p>
<button onclick="changeText()">Change</button>

<script>
function changeText() {
document.getElementById("text").innerText =
"Changed!";
}
</script>
Interactivity Example 2

Toggle Color Example:


<button onclick="toggleColor(this)">Toggle</button>

<script>
function toggleColor(btn) {
btn.style.backgroundColor = btn.style.backgroundColor
=== "blue" ? "green" : "blue";
}
</script>

You might also like