Daffodil International University · Department of Software Engineering · Marks: 40
JavaScript event listeners let you respond to user interactions. The addEventListener(event, callback) method attaches a handler to any DOM element without overwriting existing ones.
// 1. Click Event Listener const btn = document.querySelector('button'); btn.addEventListener('click', () => { console.log('Button clicked!'); }); // 2. Mouseover Event Listener btn.addEventListener('mouseover', () => { btn.style.background = 'lightblue'; }); // 3. Keydown Event Listener (on document) document.addEventListener('keydown', (e) => { console.log('Key pressed: ' + e.key); }); // 4. Submit Event Listener const form = document.querySelector('form'); form.addEventListener('submit', (e) => { e.preventDefault(); // stop default form submit console.log('Form submitted!'); }); // 5. DOMContentLoaded — runs after HTML is parsed document.addEventListener('DOMContentLoaded', () => { console.log('Page is ready!'); });
| Event Type | Trigger | Common Use Case |
|---|---|---|
click | Mouse click on element | Buttons, links, toggles |
mouseover | Mouse enters element | Hover effects, tooltips |
keydown | Key pressed on keyboard | Shortcuts, form validation |
submit | Form submission | Validate and send data |
DOMContentLoaded | DOM fully parsed | Page initialization |
Attach a click event listener to an image element. On each click: swap the image source and increment a counter displayed in a #count span.
<script> // Wait for DOM to be ready document.addEventListener('DOMContentLoaded', function() { let count = 0; const img = document.getElementById('myImage'); const counter = document.getElementById('count'); img.addEventListener('click', function() { // i. Toggle image source if (img.src.includes('image1.jpg')) { img.src = 'image2.jpg'; } else { img.src = 'image1.jpg'; } // ii. Increment click counter count++; counter.textContent = count; }); }); </script>
Click the image to toggle it and increment the counter.
Click Count:
0
Find the smallest value from the first array and the largest from the second, then return their average. Uses PHP's built-in min() and max() functions.
<?php function averageOfExtremes($arr1, $arr2) { // Get smallest from first array $smallest = min($arr1); // Get largest from second array $largest = max($arr2); // Calculate and return the average return ($smallest + $largest) / 2; } // Example Usage $arr1 = [4, 1, 2, 1, 2]; $arr2 = [2, 2, 3, 3, 5]; echo averageOfExtremes($arr1, $arr2); // Output: 3 ( min($arr1)=1 , max($arr2)=5 → (1+5)/2 = 3 ) ?>
Enter comma-separated numbers to test the logic (simulated in JS):
This solution uses three PHP OOP concepts together: an Interface (contract for setNumbers), a Trait (reusable log method), and a Class (Addition) that implements and uses both.
<?php // i. Interface — defines a contract interface Input { public function setNumbers($a, $b); } // ii. Trait — reusable block of methods trait Logger { public function log($message) { echo "[LOG] " . $message . "\n"; } } // iii. Class — implements interface, uses trait class Addition implements Input { use Logger; // Include Logger trait private $a, $b; public function setNumbers($a, $b) { $this->a = $a; $this->b = $b; $this->log("Numbers set: {$a} and {$b}"); } public function add() { $sum = $this->a + $this->b; $this->log("Performing addition..."); return $sum; } } // Instantiate and run $calc = new Addition(); $calc->setNumbers(15, 27); $result = $calc->add(); echo "Result: " . $result . "\n"; /* Output: [LOG] Numbers set: 15 and 27 [LOG] Performing addition... Result: 42 */ ?>
When a browser visits /product, Laravel processes the request through multiple layers. Each component has a distinct responsibility:
HTTP GET /product hits Laravel's router. Route::get('/product', [ProductController::class, 'index'])->name('product.index') matches the URL and dispatches to ProductController@index.
The Controller receives the request. Its index() method contains business logic. It calls the Model to fetch data, then returns a View response. It acts as the bridge between Model and View.
Product::all() queries the database via Eloquent ORM. The Model represents the data layer; it maps to the products table and returns a Collection of Product objects.
view('products.index', compact('products')) renders the Blade template with the $products variable injected. Blade processes @foreach, @if directives and outputs final HTML.
The compiled HTML is sent back as an HTTP 200 response. The browser renders the products page.
// web.php — Route definition Route::get('/product', [ProductController::class, 'index']) ->name('product.index'); // ProductController.php public function index() { $products = Product::all(); // Model: fetch all rows return view('products.index', // View: blade template compact('products')); // pass data to view } // products/index.blade.php @foreach ($products as $product) <p>{{ $product->name }}</p> @endforeach
| Component | File Location | Responsibility |
|---|---|---|
| Router | routes/web.php | Maps URL /product → Controller method |
| Controller | app/Http/Controllers/ProductController.php | Handles request logic, calls Model, returns View |
| Model | app/Models/Product.php | Interacts with database, returns data |
| View | resources/views/products/index.blade.php | Renders HTML using Blade templating |
A complete PHP application that connects to MySQL, displays a form to collect student name, roll number, and department, inserts the record, and shows a confirmation message.
<?php // ── 1. Database Connection ────────────────────── $host = 'localhost'; $dbname = 'student_db'; $user = 'root'; $pass = ''; $conn = new mysqli($host, $user, $pass, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // ── 2. Handle Form Submission ─────────────────── $message = ''; if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Sanitize inputs $name = $conn->real_escape_string($_POST['name']); $roll = $conn->real_escape_string($_POST['roll_number']); $department = $conn->real_escape_string($_POST['department']); // Insert into students table $sql = "INSERT INTO students (name, roll_number, department) VALUES ('{$name}', '{$roll}', '{$department}')"; if ($conn->query($sql) === true) { $message = "✅ Student '{$name}' added successfully!"; } else { $message = "❌ Error: " . $conn->error; } } ?> <!-- SQL to create the table --> /* CREATE TABLE students ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, roll_number VARCHAR(20) NOT NULL UNIQUE, department VARCHAR(100) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); */ <!DOCTYPE html> <html> <body> <h2>Add New Student</h2> <?php if ($message): ?> <p><?= $message ?></p> <?php endif; ?> <form method="POST" action=""> <label>Name:</label> <input type="text" name="name" required> <label>Roll Number:</label> <input type="text" name="roll_number" required> <label>Department:</label> <input type="text" name="department" required> <button type="submit">Add Student</button> </form> </body> </html>
Simulates the PHP-MySQL form behavior (data stored in memory for demo):