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>