💛 Debouncing & Throttling in JavaScript — Boost Performance Like a Pro Ever built: 👉 Search input 👉 Scroll animation 👉 Resize handler 👉 Button click spam …and your app suddenly became slow or laggy? 😵 Because events like: ▪️ scroll ▪️ resize ▪️ mousemove ▪️ keyup can fire 100+ times per second. If your API or heavy logic runs each time… 💥 Performance destroyed. That’s where Debouncing & Throttling save the day. ♦️ The Core Problem 🧠 window.addEventListener("scroll", () => { console.log("Scrolling..."); }); Scroll once → fires hundreds of times 😬 👉 Too many function calls 👉 Too many API requests 👉 UI jank We need control. ♦️ 1️⃣ Debouncing ⏳ 📌 Definition 👉 Execute function only after user stops triggering the event Think: “Wait… let them finish first” Example (Search Bar 🔍) searchInput.addEventListener("keyup", debounce(fetchResults, 500)); User types: r → ra → raj → rajk Without debounce: ❌ 4 API calls With debounce: ✅ 1 API call (after typing stops) 🧠 How It Works Every event: 👉 clears previous timer 👉 sets new timer Only last one survives. ✅ Debounce Polyfill function debounce(fn, delay) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => { fn.apply(this, args); }, delay); }; } ✅ Real-World Use Cases ✔️ Search suggestions ✔️ Auto-save ✔️ Form validation ✔️ API calls ✔️ Resize events 👉 “Execute after user stops” ♦️ 2️⃣ Throttling 🚦 📌 Definition 👉 Execute function at most once every X milliseconds Think: “Run regularly, but limit frequency” Example (Scroll Tracking 📜) window.addEventListener("scroll", throttle(updateUI, 200)); Scrolling for 5 seconds: Without throttle: ❌ 1000+ calls With throttle: ✅ ~25 calls 🧠 How It Works 👉 First call runs 👉 Next calls ignored until delay passes ✅ Throttle Polyfill function throttle(fn, limit) { let flag = true; return function (...args) { if (!flag) return; fn.apply(this, args); flag = false; setTimeout(() => { flag = true; }, limit); }; } ✅ Real-World Use Cases ✔️ Infinite scroll ✔️ Scroll animations ✔️ Button spam prevention ✔️ Window resize ✔️ Game controls 👉 “Run at controlled intervals” ♦️ Debounce vs Throttle ⚔️ 👉 Debouncing delays execution until events stop firing 👉 Throttling limits execution to fixed intervals Both: ✔️ Reduce unnecessary calls ✔️ Improve performance ✔️ Prevent UI lag ♦️ Mental Model 🧠 Debounce: “Wait till user is done” Throttle: “Slow down the calls” 🥇 Interview One-Liner Debouncing delays execution until events stop firing, while throttling limits execution to fixed intervals — both help optimize performance for high-frequency events like scroll, resize, and input. If this helped, drop a 💛 or share 🔁 Next deep dive 👉 ( Event Propagation ) - Bubbling, Capturing, and Deligation #JavaScript #JSInternals #LearnJavaScript #WebDevelopment #ProgrammingConcepts #WebDevJourney #BuildInPublic
Boost Performance with Debouncing & Throttling in JavaScript
More Relevant Posts
-
🚨 JavaScript Objects Confused Me… Until I Understood This One Thing When I started learning JavaScript, I thought objects were simple. Then I saw terms like object literals, constructor functions, "this", prototypes, "Object.create()"… And suddenly my brain went: "Wait… what is actually happening here?" 🤯 But once the puzzle clicked, everything started making sense. Here’s the simplest way I now understand JavaScript objects 👇 --- 🔹 1️⃣ Object Literals — The simplest way to create objects const user = { name: "Alex", age: 25 }; Clean. Simple. And used most of the time. --- 🔹 2️⃣ Constructor Functions — Blueprint for multiple objects function User(name, age) { this.name = name; this.age = age; } const u1 = new User("Alex", 25); Here, "this" refers to the new object being created. Think of it like a template for creating many similar objects 🧩 --- 🔹 3️⃣ Prototypes — JavaScript’s hidden superpower Instead of copying methods into every object, JavaScript shares them through prototypes. User.prototype.greet = function() { console.log("Hello!"); }; Now every "User" object can access "greet()" without duplicating memory 🚀 --- 🔹 4️⃣ Object.create() — Direct control over prototypes const person = { greet() { console.log("Hi!"); } }; const user = Object.create(person); This creates an object that inherits directly from another object. Simple concept. Very powerful in practice. --- 🔹 5️⃣ The "let" & "const" confusion with arrays and objects This confused me for a long time 👇 const arr = [1,2,3]; arr.push(4); // ✅ Works But this fails: const arr = [1,2,3]; arr = [4,5,6]; // ❌ Error Why? Because "const" protects the reference, not the content. Objects and arrays are reference types, so their internal values can change. But primitive values cannot: const a = 10; a = 20; // ❌ Error --- 🔥 Once you understand this: • Objects store references • Prototypes enable shared behavior • "this" depends on how a function is called JavaScript suddenly becomes much easier to reason about. And honestly… much more fun to work with. 🚀 --- 💬 If you're learning JavaScript: What concept confused you the most at first? Let’s help each other grow 👇 --- #javascript #webdevelopment #frontenddevelopment #softwaredevelopment #coding #programming #developer #100daysofcode #learnjavascript #codinglife #techlearning
To view or add a comment, sign in
-
🚀 Day 17 of JavaScript Daily Series JavaScript Events — click, input, change, keyup (Super Easy Hinglish + Real-Life Web Examples) Aaj hum JavaScript ka woh topic seekhenge jo websites ko truly interactive banata hai: 👉 Events Buttons click hona, input type karna, dropdown change hona, search bar me typing — yeh sab EVENTS ki wajah se possible hota hai. 💡 What Are Events? (Simple English) Events are actions that happen on a webpage. Examples: ✔ User clicks a button ✔ User types in a textbox ✔ User changes a dropdown ✔ User presses a key ✔ Mouse moves JavaScript can listen to these events and respond to them. 🧠 Hinglish Explanation Socho website ek shop hai. Customer koi bhi action kare → click, bolna, dekhna, move hona… Shopkeeper (JavaScript) turant react karta hai. “Click kiya? Chalo button ka color badal deta hoon.” “Typing shuru? Chalo search results dikhata hoon.” Today’s 4 Most Important Events 1️⃣ click 2️⃣ input 3️⃣ change 4️⃣ keyup 1️⃣ click Event — Jab User Button/Element Click Kare 📱 Example: Button text change <button id="btn">Login</button> let btn = document.getElementById("btn"); btn.addEventListener("click", function () { btn.innerText = "Logging in..."; }); Real-life use: ✔ Login button ✔ Buy Now button ✔ Like 👍 button 2️⃣ input Event — Jab User Kuch Type Kare 📱 Example: Live search bar <input id="search" placeholder="Search here..." /> <p id="output"></p> let search = document.getElementById("search"); let output = document.getElementById("output"); search.addEventListener("input", () => { output.innerText = `You typed: ${search.value}`; }); Real-life use: ✔ Search bar ✔ Live filters ✔ Form inputs 3️⃣ change Event — Jab Value Change Ho (Dropdown, Checkbox) 📱 Example: Theme selector <select id="theme"> <option value="light">Light</option> <option value="dark">Dark</option> </select> let theme = document.getElementById("theme"); theme.addEventListener("change", () => { console.log(`Theme changed to: ${theme.value}`); }); Real-life use: ✔ Country → State dropdown ✔ Dark/Light mode ✔ Payment method selection 4️⃣ keyup Event — Jab User Key Chhodta Hai 📱 Example: Password strength indicator <input id="pass" placeholder="Enter password" /> <p id="strength"></p> let pass = document.getElementById("pass"); pass.addEventListener("keyup", () => { if (pass.value.length < 6) { strength.innerText = "Weak Password"; } else { strength.innerText = "Strong Password 💪"; } }); Real-life use: ✔ OTP boxes ✔ Password checker ✔ Live validation 🔥 Quick Summary Table EventTriggerReal UseclickButton clickedActions & UI changesinputTypingSearch, formschangeValue changedDropdowns, checkboxeskeyupKey releasedValidation, search 🧠 Why Events Are Important? ✔ Website becomes interactive ✔ Real-time UI updates ✔ Forms validation ✔ Buttons functionality ✔ Every real web app uses events (React/Node bhi!) Without events → Website = Static poster.
To view or add a comment, sign in
-
Understanding the difference between the logical OR operator( || ) and Nullish Coalescing (??) in JavaScript The room is quiet. Across the table, the interviewer leans back in his chair, folds his arms, and slides a sheet of paper toward you. On it, just one line of code: const name = userInput || "Guest"; He looks up. “What happens if userInput is an empty string?” It’s a simple question. Almost too simple. But in that moment, you realize this isn’t about syntax. It’s about understanding how JavaScript thinks. About knowing the difference between something that is falsy… and something that is truly missing. And that’s where many developers discover the quiet power of ??. You answer the interviewer carefully. “If userInput is an empty string… the result will be 'Guest'.” He nods. Because in JavaScript, the logical OR operator || doesn’t ask, “Is this value missing?” It asks something else: “Is this value truthy?” And in JavaScript, an empty string "" is not truthy. Neither is 0. Neither is false. Neither is NaN. They are all falsy. So when you write: const name = userInput || "Guest"; JavaScript evaluates userInput. If it is falsy - any falsy value at all, it immediately replaces it with "Guest". An empty string? Replaced. Zero? Replaced. False? Replaced. And sometimes… that’s a problem. Imagine you’re building a dashboard. A user sets their notification count to 0 because they’ve cleared everything. That’s correct. That’s intentional. But your code says: const notificationCount = count || 10; Suddenly, the UI shows 10 notifications. Not because the user has 10. But because 0 was treated like something was wrong. That’s not a syntax error. That’s a logic error. And logic errors are the most dangerous kind - because your code runs perfectly. This is where the nullish coalescing operator ?? enters the story. Unlike ||(Logical OR operator), it doesn’t panic at every falsy value. It asks a more precise question: “Is this value actually missing?” In JavaScript, “missing” means only two things: null undefined Nothing else. So when you write: const notificationCount = count ?? 10; Now JavaScript behaves differently. If count is: 0 -> keep it false -> keep it "" -> keep it But if it’s: null -> use 10 undefined -> use 10 Suddenly, your defaults become intentional instead of accidental. Think of it this way: || is generous. Maybe too generous. It replaces anything that looks weak or empty. ?? is precise. It only steps in when something is truly absent. One replaces falsy values. The other replaces nullish values. That distinction may seem small. But in production systems - in financial apps, dashboards, admin panels, user preferences, that distinction can decide whether your application behaves correctly… or quietly lies. And the best developers? They understand not just how operators work - but what questions those operators are really asking behind the scenes.
To view or add a comment, sign in
-
💡 JavaScript Tip: 3 Advanced NaN Tricks Most Developers Don’t Know NaN stands for "Not-a-Number". It represents the result of an invalid numeric operation in JavaScript. Even though its name suggests otherwise, JavaScript still treats NaN as a number type. Here are 3 advanced NaN behaviors that many developers don’t know: -------------------------------------------------- 1️⃣ Object.is() Can Correctly Compare NaN Normally, NaN is not equal to itself: NaN === NaN // false However, Object.is() can correctly compare it: Object.is(NaN, NaN) // true Example: console.log(Object.is(NaN, NaN)); // true This is useful when you need precise value comparisons. -------------------------------------------------- 2️⃣ NaN Propagates Through Calculations Once NaN appears in a calculation, it spreads through the entire result. Example: let value = NaN; console.log(value + 5); // NaN console.log(value * 10); // NaN console.log(Math.sqrt(value)); // NaN This means a single invalid number can break an entire calculation chain. Best practice: if (Number.isNaN(value)) { console.error("Invalid number detected"); } -------------------------------------------------- 3️⃣ NaN in Arrays: includes() vs indexOf() Arrays treat NaN differently depending on the method used. Example: const arr = [NaN, 1, 2]; console.log(arr.includes(NaN)); // true console.log(arr.indexOf(NaN)); // -1 Why? - indexOf() uses strict equality (===) - includes() uses SameValueZero comparison, which correctly handles NaN. -------------------------------------------------- ✅ Best Ways to Detect NaN Use these methods: Number.isNaN(value) Object.is(value, NaN) Avoid using isNaN() because it converts values to numbers first, which can cause confusing results. -------------------------------------------------- Small JavaScript details like this can help prevent hidden bugs in real-world applications. #JavaScript #WebDevelopment #Frontend #Programming #SoftwareEngineering #almaskhan #JavaScript #fblifestyle
To view or add a comment, sign in
-
-
🚀 Understanding Hoisting and Temporal Dead Zone in JavaScript 1️⃣ Hoisting in JavaScript ("var") Hoisting means JavaScript moves variable declarations to the top of their scope during the compilation phase. When a variable is declared with "var", it is hoisted and initialized with "undefined". That is why we can sometimes access it before its declaration without getting an error. Example console.log(name); // undefined var name = "John"; Behind the scenes, JavaScript interprets it like this: var name; console.log(name); // undefined name = "John"; So with "var", the variable exists before the line where it is declared, but its value is undefined. --- 2️⃣ Temporal Dead Zone (TDZ) with "let" and "const" "let" and "const" are also hoisted, but they behave differently. They stay in a special state called the Temporal Dead Zone from the start of the scope until the line where they are declared. During this period, the variable cannot be accessed. Example console.log(age); // ReferenceError let age = 25; Here, JavaScript knows that "age" exists, but it does not allow access to it before the declaration line. This period is called the Temporal Dead Zone. --- 3️⃣ Example with "const" "const" works the same way as "let" regarding TDZ. console.log(pi); // ReferenceError const pi = 3.14; Until the declaration line is reached, "pi" remains in the Temporal Dead Zone. --- 4️⃣ Why "var" Does Not Have TDZ "var" does not have a Temporal Dead Zone because it is automatically initialized with "undefined" when hoisted. Example: console.log(score); // undefined var score = 100; Instead of throwing an error, JavaScript simply returns "undefined". --- 5️⃣ Key Difference 🔹 "var" - Hoisted to the top of scope - Automatically initialized with "undefined" - No Temporal Dead Zone 🔹 "let" and "const" - Also hoisted - Not initialized immediately - Stay in Temporal Dead Zone until declaration line - Accessing them early throws ReferenceError --- ✅ Final Takeaway - Hoisting mainly explains the behavior of "var". - Temporal Dead Zone (TDZ) explains the behavior of "let" and "const". - TDZ exists to prevent accessing variables before they are properly declared, making code safer and less error-prone. 💡 Understanding these concepts helps you avoid common JavaScript bugs and write more predictable code. #JavaScript #WebDevelopment #BackendDevelopment #Programming #LearnToCode
To view or add a comment, sign in
-
🔥 JavaScript Deep Dive: Understanding this, call(), apply(), and bind() One of the most important concepts in JavaScript is understanding how function context works. Many developers get confused with the behavior of the this keyword and how it changes depending on how a function is called. To control the value of this, JavaScript provides three powerful methods: call(), apply(), and bind(). Understanding these concepts is essential for writing clean, reusable, and predictable JavaScript code, especially when working with callbacks, event handlers, and modern frameworks. 📌 1️⃣ this Keyword In JavaScript, this refers to the object that is executing the current function. const user = { name: "Developer", greet() { console.log(`Hello ${this.name}`) } } user.greet() Output Hello Developer Here, this refers to the user object because the method is called using user.greet(). ⚡ 2️⃣ call() – Execute a function with a specific context The call() method invokes a function immediately and allows us to set the value of this. function greet(){ console.log(`Hello ${this.name}`) } const user = { name: "Developer" } greet.call(user) We can also pass arguments: function greet(city){ console.log(`${this.name} from ${city}`) } const user = { name: "Developer" } greet.call(user, "Meerut") ⚡ 3️⃣ apply() – Similar to call but arguments are passed as an array function greet(city, country){ console.log(`${this.name} from ${city}, ${country}`) } const user = { name: "Developer" } greet.apply(user, ["Meerut", "India"]) ⚡ 4️⃣ bind() – Creates a new function with a fixed this Unlike call() and apply(), the bind() method does not execute the function immediately. Instead, it returns a new function with the specified this value. function greet(){ console.log(`Hello ${this.name}`) } const user = { name: "Developer" } const greetUser = greet.bind(user) greetUser() 💡 Understanding the difference • call() executes the function immediately and arguments are passed normally (comma separated). • apply() also executes the function immediately, but arguments are passed as an array. • bind() does not execute the function immediately. Instead, it returns a new function with the this value permanently bound, which can be executed later. ⚡ Why this concept matters Understanding function context is crucial for: • Reusing functions across objects • Controlling behavior of callbacks • Writing modular and maintainable code • Working effectively with event handlers and asynchronous code Mastering these JavaScript fundamentals helps developers build more predictable and scalable applications. #JavaScript #WebDevelopment #Programming #FrontendDevelopment #Coding #SoftwareDevelopment #DeveloperJourney
To view or add a comment, sign in
-
I'm not a JavaScript master. But I still build custom functionality for clients. How? AI + basic understanding of the language. Here's the truth nobody tells you: You don't need to be an expert to solve real problems. You just need to: → Understand basic concepts → Know how to read/modify code → Ask AI the right questions The rest? AI fills in the gaps. Real examples I've built recently: 𝟭. 𝗖𝗮𝘁𝗲𝗴𝗼𝗿𝘆 𝗰𝗹𝗶𝗰𝗸 → 𝗦𝗲𝗿𝘃𝗶𝗰𝗲 𝗽𝗮𝗴𝗲 𝘄𝗶𝘁𝗵 𝗮𝗰𝘁𝗶𝘃𝗲 𝘁𝗮𝗯 Client wanted: Click a category box on homepage, land on service page with that specific tab open. My process: Knew I needed click events and URL parameters Asked AI: "How to pass category ID on click and activate matching tab on another page?" Got the code. Understood what each part does. Implemented it. Worked perfectly. 𝟮. 𝗣𝗿𝗼𝗱𝘂𝗰𝘁 𝗰𝗼𝗺𝗽𝗮𝗿𝗶𝘀𝗼𝗻 𝘄𝗶𝗱𝗴𝗲𝘁 (𝗔𝗺𝗮𝘇𝗼𝗻-𝘀𝘁𝘆𝗹𝗲) Client needed: Checkboxes on product cards. Select 2+ products, compare button appears, opens side-by-side comparison. My process: Understood: Need checkboxes, conditional button display, modal window Asked AI: "Create product comparison with checkboxes and modal in vanilla JS" Modified the output to match their WooCommerce setup Client loved it. 𝟯. 𝗖𝘂𝘀𝘁𝗼𝗺 𝘀𝗹𝗶𝗱𝗲𝗿𝘀, 𝘁𝗮𝗯𝘀, 𝗮𝗻𝗶𝗺𝗮𝘁𝗶𝗼𝗻𝘀 Libraries exist. But sometimes you need something specific. AI writes the base. I customize it to fit the design and behavior the client wants. The key difference: I understand WHAT the code is doing. Not memorizing syntax. Not writing everything from scratch. But knowing: How event listeners work What DOM manipulation means How to debug when something breaks When to use vanilla JS vs jQuery This is how modern development works. You don't need to be a coding genius anymore. You need to: Understand fundamentals Know how to communicate with AI Read and modify code intelligently "But isn't that cheating?" No. Using a calculator isn't cheating in accounting. Using Figma templates isn't cheating in design. Using AI isn't cheating in development. It's just a better tool. What you DO need to learn: ✓ Basic JavaScript concepts (variables, functions, events) ✓ How to select DOM elements ✓ Basic debugging skills ✓ How to read documentation Without this foundation? AI gives you code you can't understand or fix. With this foundation? AI becomes a superpower. 𝗠𝘆 𝘄𝗼𝗿𝗸𝗳𝗹𝗼𝘄 𝗻𝗼𝘄: Understand what client needs Break it into logical steps Ask AI for code structure Review, understand, and customize Test and debug Deliver Faster than learning everything from scratch. Better results than using generic plugins. Do you use AI in your development workflow or still doing everything manually? #JavaScript #WebDevelopment #AI #WordPress #CodingTips
To view or add a comment, sign in
-
-
📌 Just finished reading the JavaScript documentation on Prototypes — here's what I actually understood 🧵 I spent time going through the official MDN docs on JavaScript prototypes, and wanted to share here— 🔺 What is a Prototype? Every object in JavaScript has a hidden internal link to another object — called its prototype. Think of it as a "parent" object that the current object can borrow properties and methods from. When you try to access a property on an object and it's not found directly on that object, JavaScript automatically looks up to its prototype. If it's not there either, it goes up again — until it reaches null. This chain of lookups is called the prototype chain. 🔺 Why does this exist? JavaScript needed a way to share behavior across multiple objects without duplicating code or wasting memory. Instead of giving every object its own copy of a method, you define the method once on a prototype — and all objects linked to that prototype can use it. This is memory-efficient and keeps things organized. 🔺 How it works — a simple example: function Person(name) { this.name = name; } // Adding a method to the prototype Person.prototype.greet = function () { console.log("Hi, I'm " + this.name); }; const alice = new Person("Alice"); const bob = new Person("Bob"); alice.greet(); // Hi, I'm Alice bob.greet(); // Hi, I'm Bob // Both share the SAME greet function — not two separate copies console.log(alice.greet === bob.greet); // true Here, greet lives on Person.prototype — not on alice or bob individually. JavaScript finds it by walking up the prototype chain. 🔺 When do you actually use this in real projects? Constructor functions — before ES6 classes, this was the standard way to create objects with shared behavior. Shared methods — placing utility methods on a prototype so all instances access one definition. Memory efficiency — especially relevant when creating many instances of the same object type. Understanding built-ins — methods like .map(), .filter(), .toString() all live on prototype objects (Array.prototype, Object.prototype, etc.). 🔺 One thing that tripped me up: The difference between an object's prototype (accessed via Object.getPrototypeOf(obj)) and the prototype property on a constructor function (Person.prototype) — they're related but not the same thing. Worth reading carefully. 🔺 My question to other developers: Do you think understanding prototypes is still essential for modern JavaScript development, or is it more of a "good to know" concept now? Would love to hear how others think about this. 👇 #JavaScript #WebDevelopment #Frontend #LearnInPublic #JS
To view or add a comment, sign in
-
-
🚀 Day 13 of JavaScript Daily Series JavaScript Strings — slice, substring, toUpperCase, trim (Super Easy Hinglish + Real-Life Examples) Aaj hum JavaScript ke 4 most useful string methods seekhenge. Yeh daily life coding me 100% use hote hain — chahe forms ho, search bars ho, validation ho ya UI formatting. 📝 What is a String? (Simple English Definition) A string is a sequence of characters used to store text like names, messages, sentences, etc. Example: let name = "Ritesh Singh"; 1️⃣ slice() — Cut & Extract Part of the String 🔹 Definition Returns a portion of string from start index to end index (end not included). 🧠 Hinglish Explanation Socho tum movie clip ka ek scene cut karke nikalna chahte ho → yahi slice karta hai. 📱 Real-Life Example Instagram username crop karna: let username = "aapanrasoi_official"; let shortName = username.slice(0, 10); console.log(shortName); // "aapanraso" 2️⃣ substring() — Extract Part of String (Like slice, but safer) 🔹 Definition Works like slice but doesn’t accept negative indexes. 🧠 Hinglish Explanation Slice ka hi shareef version — negative cheezein nahi leta. 😄 📱 Example let text = "JavaScript"; console.log(text.substring(4, 10)); // "Script" 3️⃣ toUpperCase() — Convert to CAPITAL Letters 🔹 Definition Returns the string in uppercase. 🧠 Hinglish Explanation Whatsapp pe aise lagta hai jaise koi chillaa kar message bhej raha ho. 😆 📱 Example let city = "varanasi"; console.log(city.toUpperCase()); // "VARANASI" 4️⃣ trim() — Remove Extra Spaces 🔹 Definition Removes spaces from start and end. 🧠 Hinglish Explanation Form bharte time users extra space daal dete hain, trim unko clean kar deta hai. 📱 Real-Life Example (Form Input Clean) let email = " ritesh@gmail.com "; console.log(email.trim()); // "ritesh@gmail.com" 🔥 Quick Summary Table MethodKaamReal Useslice()Part nikalnaUsername / Title Shortensubstring()Safe extractionWord pickingtoUpperCase()Text ko caps meLabels / Highlightstrim()Extra space hatanaForm inputs 🧠 Why These 4 Methods Matter? ✔ Clean data ✔ Better UI ✔ Faster string manipulation ✔ Interviews me 100% pooch lete hain
To view or add a comment, sign in
-
Day 74 – JavaScript DOM Events & Advanced Manipulation Today I explored Events in JavaScript DOM and how they make websites interactive and dynamic. 🔹 What Are Events? An event is an action that happens in the browser. Some common events: ✔️ click ✔️ dblclick ✔️ mouseover ✔️ submit ✔️ input Events allow us to respond when users interact with the webpage. 🔹 onClick Event Trigger an action when a button is clicked: function fun(){ document.getElementById("demo").innerHTML = "I Love India"; } <button onclick="fun()">Change</button> ✅ Single click → Function executes ✅ Content or style can be changed dynamically 🔹 onMouseOver Event Trigger an action when the mouse moves over an element: <p onmouseover="ff()" class="demo"></p> function ff(){ document.querySelector(".demo").style.background = "grey"; } 🔹 Input Receiving & Validation function fun(){ let x = document.getElementById("k").value; let text; if(isNaN(x) || x < 10 || x === ''){ text = "Not Ok"; } else { text = "Ok"; } document.getElementById("demo").innerHTML = text; } ✅ Checks if value is a number ✅ Validates conditions ✅ Displays result dynamically 🔹 Alternating Colors (Mini Project) Example: Heart icon changes color on each click: let c = 0; function change(){ c++; if(c % 2 === 1){ document.getElementById("demo").style.color = "red"; } else { document.getElementById("demo").style.color = "black"; } } This demonstrates logic + DOM manipulation together. 🔹 addEventListener() Better and cleaner way to attach events: document.getElementById("my_btn") .addEventListener("click", displayDate); function displayDate(){ document.getElementById("demo").innerHTML = Date(); } ✅ Keeps HTML clean ✅ Allows multiple events ✅ More professional approach 🔹 Creating Elements Using JavaScript let li = document.createElement("li"); let text = document.createTextNode("Orange"); li.appendChild(text); document.getElementById("my_list").appendChild(li); ✔️ createElement() ✔️ createTextNode() ✔️ appendChild() Dynamic content creation = powerful frontend development. 🔹 Setting Attributes Dynamically element.setAttribute("class", "my_div"); We can dynamically assign: class id name etc. 🔹 Key Takeaway Today’s learning helped me understand: ✨ How user actions trigger events ✨ How to validate forms ✨ How to dynamically create & move elements ✨ How to manipulate styles using JavaScript ✨ Why addEventListener() is preferred Each day, getting closer to becoming a strong Frontend Developer #JavaScript #DOM #WebDevelopment #Frontend
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development