20 practical JavaScript Event practice questions

🧪 JavaScript Events – Practice Questions

🟢 Beginner Level (1–7)

1.

Create a button. When clicked, change its text to “Clicked!”.


2.

Create a button that shows an alert message when double-clicked.


3.

Create a div. Change its background color when mouse hovers over it.


4.

Create an input box. Display text “Typing…” when user starts typing.


5.

Create an input field. Show the typed value in a <p> tag.


6.

Create a button. When clicked, hide a paragraph.


7.

Create a button. When clicked, show a hidden paragraph.


🟡 Intermediate Level (8–14)

8.

Create a form. Prevent page reload on submit and show entered name in alert.


9.

Detect which key is pressed using keyboard event and display it.


10.

Create a button that changes color every time it is clicked.


11.

Create multiple buttons. Show which button was clicked using event target.


12.

Create a dropdown (select). Show selected value when changed.


13.

Create an input field. When it loses focus (blur), validate if it’s empty.


14.

Create a character counter for a textarea (live update while typing).


🔴 Advanced Level (15–20)

15.

Demonstrate event bubbling using parent and child elements.


16.

Stop event bubbling when clicking child element.


17.

Use event delegation to handle clicks on dynamically added list items.


18.

Create a to-do list where new items can be added and clicked (use delegation).


19.

Create a keyboard shortcut:
👉 Press “Enter” to submit form
👉 Press “Escape” to clear input


20.

Build a small typing detector:

  • Show “User is typing…”
  • After 1 second of no typing → show “Stopped typing”

(Hint: use setTimeout)


🚀 Bonus Challenge (Real Project)

👉 Build a Click Counter App

  • Button click increases count
  • Reset button resets count
  • Show message when count > 10

💡 Pro Tip

If you can solve:

  • Q1–7 → Basic understanding
  • Q8–14 → Job-ready
  • Q15–20 → Strong developer level

Mini project (calculator / typing speed tester)

8️⃣ JavaScript Events

JavaScript events allow you to make your website interactive.
An event happens when a user does something like clicking, typing, or submitting a form.

👉 Example:

  • Click → event
  • Typing → event
  • Hover → event

🖱️ 1. Mouse Events

These events happen when the user uses the mouse.

Common Mouse Events:

  • click → when button is clicked
  • dblclick → double click
  • mouseover → when mouse enters element
  • mouseout → when mouse leaves element

Example:

<button onclick="showMessage()">Click Me</button><script>
function showMessage() {
alert("Button clicked!");
}
</script>

⌨️ 2. Keyboard Events

These events happen when user types on keyboard.

Common Keyboard Events:

  • keydown → key pressed
  • keyup → key released
  • keypress (old, avoid now)

Example:

<input type="text" onkeyup="checkInput()"><script>
function checkInput() {
console.log("User is typing...");
}
</script>

📝 3. Form Events

These events are used in forms.

Common Form Events:

  • submit → when form is submitted
  • change → when input value changes
  • focus → when input is selected
  • blur → when input loses focus

Example:

<form onsubmit="handleSubmit(event)">
<input type="text" required>
<button type="submit">Submit</button>
</form><script>
function handleSubmit(e) {
e.preventDefault(); // stop page reload
alert("Form submitted!");
}
</script>

🔄 4. Event Bubbling

Event bubbling means:

👉 Event starts from child element → goes up to parent

Example:

<div onclick="parentClick()" style="padding:20px; background:lightblue;">
<button onclick="childClick()">Click Me</button>
</div><script>
function parentClick() {
alert("Parent clicked");
}function childClick() {
alert("Button clicked");
}
</script>

👉 When you click button:

  1. Button event runs
  2. Then parent event runs

Stop Bubbling:

function childClick(event) {
event.stopPropagation();
alert("Only button clicked");
}

🎯 5. Event Delegation

Event delegation means:

👉 Instead of adding events to many elements,
you add one event to parent

Why use it?

  • Better performance
  • Works for dynamic elements

Example:

<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul><script>
document.getElementById("list").addEventListener("click", function(e) {
if (e.target.tagName === "LI") {
alert(e.target.innerText);
}
});
</script>

👉 One event handles all <li> items


🧪 Practice Tasks

✅ 1. Interactive Button

<button id="btn">Click Me</button><script>
document.getElementById("btn").addEventListener("click", function() {
this.innerText = "Clicked!";
});
</script>

✅ 2. Keyboard Typing Detector

<input type="text" id="inputBox" placeholder="Type something"><p id="output"></p><script>
document.getElementById("inputBox").addEventListener("keyup", function(e) {
document.getElementById("output").innerText =
"You typed: " + e.target.value;
});
</script>

💡 Pro Tips (Important for Interviews)

  • Use addEventListener() instead of inline events
  • Use event object (e) for advanced control
  • Avoid keypress (deprecated)
  • Use event delegation in dynamic apps (like lists, tables)

30 DOM Practice Questions

🟢 Beginner Level (1–10)

  1. Select an element with id "title" and print it in console.
  2. Change the text of a paragraph using innerHTML.
  3. Change background color of a div to blue.
  4. Select all elements with class "box" and print their length.
  5. Change text of a button when it is clicked.
  6. Add a new <li> item inside a <ul>.
  7. Remove an element from the page using JavaScript.
  8. Change an image src on button click.
  9. Show an alert when user clicks a button.
  10. Change font size of a heading using JavaScript.

🟡 Intermediate Level (11–20)

  1. Toggle a class "dark-mode" on body when button is clicked.
  2. Count number of <p> tags in a page.
  3. Loop through multiple elements and change their color.
  4. Create a button that hides and shows a div.
  5. Get value from input field and display it in a div.
  6. Change placeholder text of an input field.
  7. Validate if input field is empty on button click.
  8. Add multiple list items dynamically using array.
  9. Create a counter (increase/decrease value on button click).
  10. Detect mouse hover and change element color.

🔵 Advanced Level (21–30)

  1. Create a live character counter for a textarea.
  2. Build a simple image slider (next/previous buttons).
  3. Validate email format using JavaScript.
  4. Highlight selected menu item when clicked.
  5. Create a dropdown menu that opens on click.
  6. Build a tab system (click → show content).
  7. Create a to-do list (add + delete tasks).
  8. Detect keyboard input and show pressed key.
  9. Prevent form submission if validation fails.
  10. Create a real-time search filter (filter list items as user types).

🔥 Bonus Challenge (Real-world)

👉 Build a mini app combining multiple DOM concepts:

  • Dark mode toggle
  • Form validation
  • To-do list
  • Counter

💡 Tip (Very Important)

👉 First 10 → Basics
👉 Next 10 → Logic building
👉 Last 10 → Real-world projects

7️⃣ DOM Manipulation (VERY IMPORTANT)

🧠 What is DOM?

DOM = Document Object Model

👉 When a webpage loads, the browser converts HTML into a tree structure (objects).

Example HTML:

<h1 id="title">Hello</h1>

DOM representation:

Document
└── h1 (id="title")
└── "Hello"

👉 JavaScript can access and modify this structure.


🎯 Selecting Elements

To change anything on a page, first you must select it.


🔹 getElementById

let element = document.getElementById("title");
console.log(element);

👉 Selects element by ID
👉 Returns single element


🔹 getElementsByClassName

let items = document.getElementsByClassName("box");
console.log(items);

👉 Selects elements by class
👉 Returns HTMLCollection (array-like)


🔹 querySelector

let element = document.querySelector(".box");

👉 Selects first matching element
👉 Uses CSS selectors


🔹 querySelectorAll

let elements = document.querySelectorAll(".box");

👉 Selects all matching elements
👉 Returns NodeList


✏️ Changing HTML

🔹 innerHTML

document.getElementById("title").innerHTML = "Welcome Aditya!";

👉 Changes content inside element


🔹 textContent

element.textContent = "New Text";

👉 Safer than innerHTML (no HTML tags executed)


🎨 Changing CSS

🔹 style property

element.style.color = "red";
element.style.backgroundColor = "yellow";

🔹 Add / Remove Class

element.classList.add("active");
element.classList.remove("active");
element.classList.toggle("dark");

👉 Best practice for styling


⚡ Event Handling

👉 Events = user actions

Examples:

  • click
  • hover
  • submit
  • keypress

🔹 onclick

<button onclick="changeText()">Click</button>
function changeText() {
document.getElementById("title").innerHTML = "Clicked!";
}

🔹 onmouseover

<div onmouseover="hoverEffect()">Hover me</div>
function hoverEffect() {
console.log("Mouse over");
}

🔹 onsubmit

<form onsubmit="return validateForm()">
<input type="text" id="name">
<button type="submit">Submit</button>
</form>
function validateForm() {
let name = document.getElementById("name").value; if (name === "") {
alert("Name required");
return false;
}
}

👉 return false stops form submission


🚀 Practice Projects

These are must-do to master DOM 👇


🌙 1. Dark Mode Toggle

<button onclick="toggleDark()">Dark Mode</button>
function toggleDark() {
document.body.classList.toggle("dark");
}
.dark {
background: black;
color: white;
}

🖼️ 2. Image Slider

<img id="slider" src="img1.jpg" width="300">
<button onclick="next()">Next</button>
let images = ["img1.jpg", "img2.jpg", "img3.jpg"];
let index = 0;function next() {
index = (index + 1) % images.length;
document.getElementById("slider").src = images[index];
}

📋 3. Form Validation

function validateForm() {
let email = document.getElementById("email").value; if (email === "") {
alert("Email required");
return false;
} if (!email.includes("@")) {
alert("Invalid email");
return false;
}
}

🧠 Pro Tips

  • Prefer querySelector (modern)
  • Use classList instead of style
  • Avoid too much innerHTML
  • Use addEventListener (advanced)

Example:

button.addEventListener("click", function() {
console.log("Clicked");
});

6️⃣ Objects in JavaScript (Simple + Practical)


🔹 What is an Object?

An object is a collection of data stored in key-value pairs.

👉 Real-life example:
A student has name, age, marks → all grouped together.

let student = {
name: "Aditya",
age: 20,
marks: 85
};

🔹 Object Properties

Properties are variables inside an object.

let student = {
name: "Aditya",
age: 20
};console.log(student.name); // Aditya
console.log(student["age"]); // 20

👉 Two ways to access:

  • Dot notation → student.name
  • Bracket notation → student["name"]

🔹 Object Methods

Methods are functions inside an object.

let student = {
name: "Aditya",
greet: function() {
return "Hello " + this.name;
}
};console.log(student.greet()); // Hello Aditya

👉 this refers to the current object.


🔹 Nested Objects

Objects inside another object.

let student = {
name: "Aditya",
address: {
city: "Delhi",
pincode: 110001
}
};console.log(student.address.city); // Delhi

🔹 Object.keys()

Returns all keys (property names) in an array.

let student = {
name: "Aditya",
age: 20
};console.log(Object.keys(student));
// ["name", "age"]

🔹 Object.values()

Returns all values in an array.

console.log(Object.values(student));
// ["Aditya", 20]

🔹 Object.entries()

Returns key-value pairs as arrays.

console.log(Object.entries(student));
// [["name", "Aditya"], ["age", 20]]

🧠 Practice: Student Management System

🎯 Goal:

Store and manage student data using objects.


✅ Example:

let student = {
name: "Rahul",
age: 21,
marks: {
math: 80,
science: 75,
english: 85
},
getTotal: function() {
return this.marks.math + this.marks.science + this.marks.english;
}
};// Access data
console.log(student.name);// Nested object
console.log(student.marks.math);// Method
console.log("Total Marks:", student.getTotal());// Keys, values, entries
console.log(Object.keys(student));
console.log(Object.values(student));
console.log(Object.entries(student));

🚀 Mini Project (Multiple Students)

let students = [
{
name: "Amit",
age: 20,
marks: 80
},
{
name: "Priya",
age: 22,
marks: 90
}
];// Loop through students
students.forEach(function(stu) {
console.log(stu.name + " - " + stu.marks);
});

🔥 Practice Tasks for Students

  1. Create an object for 5 students
  2. Add a method to calculate average marks
  3. Print all student names using Object.keys()
  4. Find student with highest marks
  5. Add nested object for address

50 JavaScript Array Practice Questions

🟢 Basic Level (1–15)

  1. Create an array of 5 numbers and print it.
  2. Create an array of 3 fruits and access the second element.
  3. Find the length of an array.
  4. Add a new element at the end using push().
  5. Remove the last element using pop().
  6. Add an element at the beginning using unshift().
  7. Remove the first element using shift().
  8. Create an array and print all elements using for loop.
  9. Print all elements using forEach().
  10. Replace the second element of an array.
  11. Check if an element exists using includes().
  12. Convert array to string using join().
  13. Reverse an array using reverse().
  14. Sort an array of numbers.
  15. Find index of a value using indexOf().

🟡 Intermediate Level (16–30)

  1. Create an array and double each value using map().
  2. Convert all strings to uppercase using map().
  3. Filter even numbers using filter().
  4. Filter numbers greater than 50.
  5. Find sum of array using reduce().
  6. Find maximum value using reduce().
  7. Count total elements using reduce().
  8. Remove duplicate values from an array.
  9. Merge two arrays.
  10. Find common elements between two arrays.
  11. Slice first 3 elements using slice().
  12. Remove 2 elements from index 1 using splice().
  13. Insert values using splice().
  14. Flatten a nested array (basic).
  15. Check if all elements are positive using every().

🟠 Advanced Level (31–50)

  1. Check if any number is greater than 100 using some().
  2. Create an array of objects (students with marks).
  3. Filter students who scored above 80.
  4. Use map() to extract student names.
  5. Calculate total marks of students using reduce().
  6. Sort students by marks (ascending).
  7. Sort students by marks (descending).
  8. Group numbers into even and odd arrays.
  9. Find second largest number in array.
  10. Rotate array to the right by 1 position.
  11. Count frequency of each element.
  12. Find missing number in sequence (1–10).
  13. Remove falsy values (false, 0, "", null, undefined).
  14. Convert array of strings to numbers.
  15. Find longest string in array.
  16. Chunk array into smaller arrays (size 2).
  17. Shuffle an array randomly.
  18. Find intersection of multiple arrays.
  19. Implement your own map() function.
  20. Build a mini Todo app using array methods.

🎯 Bonus Challenge

  • Build Student Result Dashboard
  • Create Shopping Cart System
  • Make Notes App using Arrays
  • Build Quiz App (Questions stored in array)

5️⃣ Arrays in JavaScript

📌 What is an Array?

An array is a collection of values stored in a single variable.

let fruits = ["Apple", "Banana", "Mango"];

🛠️ Creating Arrays

1. Using []

let numbers = [10, 20, 30];

2. Using Array constructor

let numbers = new Array(10, 20, 30);

🎯 Accessing Elements

let fruits = ["Apple", "Banana", "Mango"];console.log(fruits[0]); // Apple
console.log(fruits[1]); // Banana

👉 Index starts from 0


⚙️ Basic Array Methods

➕ push() → Add at end

let arr = [1, 2];
arr.push(3);console.log(arr); // [1, 2, 3]

➖ pop() → Remove from end

let arr = [1, 2, 3];
arr.pop();console.log(arr); // [1, 2]

⬅️ shift() → Remove from start

let arr = [1, 2, 3];
arr.shift();console.log(arr); // [2, 3]

➡️ unshift() → Add at start

let arr = [2, 3];
arr.unshift(1);console.log(arr); // [1, 2, 3]

✂️ splice() → Add/Remove/Replace

let arr = [1, 2, 3, 4];// remove 2 elements from index 1
arr.splice(1, 2);console.log(arr); // [1, 4]

👉 Add elements:

let arr = [1, 4];
arr.splice(1, 0, 2, 3);console.log(arr); // [1, 2, 3, 4]

🍰 slice() → Copy part of array

let arr = [1, 2, 3, 4];let newArr = arr.slice(1, 3);console.log(newArr); // [2, 3]

👉 Original array does not change


🚀 Advanced Methods

🔁 map() → Transform array

let numbers = [1, 2, 3];let result = numbers.map(num => num * 2);console.log(result); // [2, 4, 6]

🔍 filter() → Select elements

let numbers = [1, 2, 3, 4];let even = numbers.filter(num => num % 2 === 0);console.log(even); // [2, 4]

➕ reduce() → Single value result

let numbers = [1, 2, 3, 4];let sum = numbers.reduce((total, num) => total + num, 0);console.log(sum); // 10

🔄 forEach() → Loop through array

let fruits = ["Apple", "Banana"];fruits.forEach(fruit => {
console.log(fruit);
});

🧠 Practice Projects

🧑‍🎓 1. Student Marks System

let marks = [80, 75, 90, 60];// total marks
let total = marks.reduce((sum, m) => sum + m, 0);// average
let avg = total / marks.length;// passed students (>= 70)
let passed = marks.filter(m => m >= 70);console.log("Total:", total);
console.log("Average:", avg);
console.log("Passed:", passed);

✅ 2. Todo List

let todos = [];// add task
function addTask(task) {
todos.push(task);
}// remove last task
function removeTask() {
todos.pop();
}// show tasks
function showTasks() {
todos.forEach((task, index) => {
console.log(index + ": " + task);
});
}// usage
addTask("Study JS");
addTask("Practice Arrays");
showTasks();removeTask();
showTasks();

JavaScript Functions – Practice Questions

🔹 Basic Level (1–7)

  1. Create a function that prints "Hello World".
  2. Create a function that takes a name as input and prints:
    👉 "Hello, <name>"
  3. Write a function to add two numbers and return the result.
  4. Create a function to check if a number is even or odd.
  5. Write a function that returns the square of a number.
  6. Create a function that converts Celsius to Fahrenheit.
  7. Write a function that finds the maximum of two numbers.

🔹 Intermediate Level (8–14)

  1. Create a function to calculate the area of a circle.
  2. Write a function that counts the number of vowels in a string.
  3. Create a function that reverses a string.
  4. Write a function that checks if a number is prime.
  5. Create a function that takes an array and returns the sum of all elements.
  6. Write a function that finds the largest number in an array.
  7. Create a function that calculates factorial of a number.

🔹 Advanced Level (15–20)

  1. Convert a normal function into an arrow function.
  2. Write a function with default parameters (e.g., greet user with default name).
  3. Create a function expression that multiplies two numbers.
  4. Write a callback function example:
    👉 One function should accept another function as argument.
  5. Create a function that filters even numbers from an array.
  6. Build a mini calculator using functions:
    👉 add, subtract, multiply, divide

🚀 for students

👉 Combine everything:

  • Take user input
  • Use functions
  • Display result in HTML

Mini project using functions (calculator app)

4️⃣ Functions (JavaScript)

🔹 What is a Function?

A function is a block of code that performs a specific task and can be reused.

👉 Instead of writing code again and again, you call a function.

function greet() {
console.log("Hello!");
}
greet(); // calling function

🔹 Function Declaration

Defined using the function keyword.

function add(a, b) {
return a + b;
}console.log(add(5, 3)); // 8

✔️ Can be called before declaration (hoisting)


🔹 Function Expression

Function stored inside a variable.

const multiply = function(a, b) {
return a * b;
};console.log(multiply(4, 3)); // 12

❌ Cannot call before definition


🔹 Arrow Functions (ES6)

Short and modern syntax.

const divide = (a, b) => {
return a / b;
};console.log(divide(10, 2)); // 5

👉 Short form:

const square = x => x * x;

🔹 Parameters & Arguments

  • Parameters → variables in function
  • Arguments → actual values passed
function greet(name) { // parameter
console.log("Hello " + name);
}greet("Aditya"); // argument

🔹 Return Values

Functions can return a value.

function sum(a, b) {
return a + b;
}let result = sum(2, 3);
console.log(result); // 5

🔹 Default Parameters

Set default value if no argument is passed.

function greet(name = "Guest") {
console.log("Hello " + name);
}greet(); // Hello Guest
greet("Aditya"); // Hello Aditya

🔹 Callback Functions

A function passed as an argument to another function.

function greet(name, callback) {
console.log("Hello " + name);
callback();
}function sayBye() {
console.log("Goodbye!");
}greet("Aditya", sayBye);

🧪 Practice Programs

1️⃣ Age Calculator

function calculateAge(birthYear) {
let currentYear = new Date().getFullYear();
return currentYear - birthYear;
}let age = calculateAge(2000);
console.log("Your age is:", age);

2️⃣ Simple Interest Calculator

Formula:
👉 SI = (P × R × T) / 100

function simpleInterest(p, r, t) {
return (p * r * t) / 100;
}let si = simpleInterest(10000, 5, 2);
console.log("Simple Interest:", si);

Mini Projects for Students (JavaScript)

🟢 Beginner Level Projects

1. 🎯 Number Guessing Game

👉 User guesses a number between 1–10

Concepts:

  • while loop
  • if...else

Extra ideas:

  • Add attempt counter
  • Show “Too high / Too low”

2. 🔢 Multiplication Table Generator

👉 User enters a number → show table

Concepts:

  • for loop

3. 🧮 Simple Calculator

👉 Perform +, −, ×, ÷

Concepts:

  • switch
  • user input

Bonus:

  • Handle divide by 0

4. 🔐 Even/Odd Checker Tool

👉 Input number → show result

Concepts:

  • if else

5. 📊 Marks Grade Calculator

👉 Input marks → show grade

Concepts:

  • else if

🟡 Intermediate Level Projects

6. 🔁 Reverse Number Tool

👉 Input number → reverse it

Concepts:

  • loops
  • math logic

7. 🔍 Prime Number Checker

👉 Check if number is prime

Concepts:

  • for loop
  • condition logic

8. 🔢 Fibonacci Generator

👉 Generate series

Concepts:

  • loops
  • variables

9. 🧠 Palindrome Checker

👉 Check if number/string same reverse

Concepts:

  • loops
  • string handling

10. 🎲 Random Password Generator

👉 Generate simple password

Concepts:

  • loops
  • random numbers

🔴 Advanced Mini Projects

11. 🎮 Quiz App (Console or Basic UI)

👉 Ask questions → show score

Concepts:

  • loops
  • if else
  • arrays

12. 🧾 Bill Split Calculator

👉 Split bill among people

Concepts:

  • math + input

13. ⏱ Countdown Timer

👉 Count down from number

Concepts:

  • loops / setInterval

14. 🧩 Pattern Generator Tool

👉 Print star/number patterns

Concepts:

  • nested loops

15. 🎯 Limited Attempt Guessing Game

👉 Only 5 chances

Concepts:

  • loops + break

💡Important for Students

  • Add HTML + CSS UI
  • Use buttons & input fields
  • Show results on screen (not just console)