🚀 JavaScript Simplified Series — Day 23 A website without interaction is boring… 😴 No clicks No input No response Just static content ❌ 🤔 Real Question How does a website know… 👉 When you click a button? 👉 When you type in an input? 👉 When you scroll? This is where Events come in. 🔥 What is an Event? An event is something that happens in the browser 👉 Click 👉 Hover 👉 Key press 👉 Scroll JavaScript listens to these events and reacts. 🔹 Adding an Event Listener let button = document.querySelector("button") button.addEventListener("click", function() { console.log("Button Clicked") }) 👉 When user clicks → function runs 🔹 Common Events // Click button.addEventListener("click", fn) // Input input.addEventListener("input", fn) // Key press document.addEventListener("keydown", fn) 🔹 Real Example let btn = document.querySelector("button") let heading = document.querySelector("h1") btn.addEventListener("click", function() { heading.innerText = "You clicked the button!" }) 👉 Click → text change 😎 🔹 Event Object JavaScript automatically gives event details button.addEventListener("click", function(event) { console.log(event) }) 📌 You get info like: 👉 Mouse position 👉 Target element 👉 Key pressed 🔥 Real Life Example Think of a doorbell 🔔 You press → sound comes 👉 Action → Reaction Same in JS: User action → Event → Response 🔥 Simple Summary Event → user action addEventListener → listen to event function → response 💡 Programming Rule Websites react to users. Events make that possible. If you want to learn JavaScript in a simple and practical way, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling (Next Post) Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
JavaScript Simplified: Understanding Events
More Relevant Posts
-
🚀 JavaScript Simplified Series — Day 26 You click a button… But nothing happens immediately 😳 Instead… it waits. Then suddenly → response comes. How does JavaScript handle this? 🤔 🔥 The Problem JavaScript runs line by line (synchronously) console.log("Start") console.log("Process") console.log("End") 👉 Output: Start Process End Everything runs one after another 😵 But Real World is Different Think about: 👉 API calls 👉 File loading 👉 Timers They take time ⏳ If JavaScript waits… everything will freeze ❌ 🔥 Solution → Asynchronous JavaScript JavaScript can handle tasks without blocking execution 🔹 Example with setTimeout console.log("Start") setTimeout(() => { console.log("Delayed Task") }, 2000) console.log("End") 👉 Output: Start End Delayed Task 🔍 What’s happening? 👉 setTimeout runs later 👉 JavaScript doesn’t wait 👉 Code continues execution 🔹 Callback in Async setTimeout(function() { console.log("Task Done") }, 1000) 👉 Function runs after delay 📌 This function is a callback 🔥 Real Life Example Ordering food 🍔 You order → wait Meanwhile → you do other work Food arrives later 👉 That’s async behavior 🔥 Simple Summary Sync → line by line execution Async → non-blocking execution Callback → function runs later 💡 Programming Rule Don’t block execution. Let JavaScript handle tasks asynchronously. If you want to learn JavaScript in a simple and practical way, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling Day 25 → Event Delegation Day 26 → Async JavaScript (Callbacks) Day 27 → Promises (Next Post) Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
🚀 JavaScript: The Art of Execution Context & Hoisting (Why it REALLY matters) If you’ve ever wondered why JavaScript behaves the way it does, the answer lies in two core concepts: 👉 Execution Context 👉 Hoisting These aren’t just theory—they define how your code actually runs under the hood. 🧠 1. Execution Context — The Engine Behind Every Line Every time JavaScript runs code, it creates an Execution Context. There are mainly two types: Global Execution Context (GEC) → created when your program starts Function Execution Context (FEC) → created every time a function is invoked 🔄 How it works: Each execution context is created in two phases: 1️⃣ Memory Creation Phase (Hoisting Phase) Variables → stored as undefined Functions → stored with full definition 2️⃣ Code Execution Phase Values are assigned Code runs line by line ⚡ 2. Hoisting — Not Magic, Just Memory Allocation Hoisting is often misunderstood. It doesn’t “move code up”— 👉 it simply means JavaScript allocates memory before execution begins 🔍 Example that explains EVERYTHING console.log(a); // ? console.log(b); // ? console.log(myFunc); // ? var a = 10; let b = 20; function myFunc() { console.log("Hello JS"); } 🧠 Memory Phase: a → undefined b → (in Temporal Dead Zone) myFunc → full function stored 🏃 Execution Phase: console.log(a); // undefined console.log(b); // ❌ ReferenceError console.log(myFunc); // function definition 💣 The TRICKY Part (Arrow Functions vs Normal Functions) console.log(add); const add = () => { return 2 + 3; }; ❓ Output? 👉 ReferenceError: Cannot access 'add' before initialization Why? Because: const variables are hoisted but not initialized They stay in the Temporal Dead Zone (TDZ) So unlike normal functions: console.log(sum); // works function sum() { return 5; } 👉 Function declarations are fully hoisted with definition 👉 But arrow functions behave like variables ❌ 🔥 Key Takeaways ✔ JavaScript creates a new execution context for every function ✔ Memory is allocated before execution starts ✔ var → hoisted as undefined ✔ let / const → hoisted but in TDZ ✔ Function declarations → fully hoisted ✔ Arrow functions → treated like variables 🎯 Why This Matters Understanding this helps you: Debug errors faster ⚡ Write predictable code 🧩 Master interviews 💼 Think like the JavaScript engine 🧠 💡 JavaScript is not weird—you just need to think in terms of execution context. #JavaScript #WebDevelopment #Frontend #Coding #100DaysOfCode #AkshaySaini #Hoisting #ExecutionContext
To view or add a comment, sign in
-
🚀 JavaScript Simplified Series — Day 20 Till now… you’ve learned JavaScript concepts. But here’s the real question 👇 👉 How does JavaScript actually interact with a website? How does a button click work? How does text change on screen? How does a form submit? This is where DOM comes in. 🔥 What is DOM? DOM stands for: 👉 Document Object Model Simple words me: DOM is a tree-like structure of your HTML page which JavaScript can read and modify. 🔹 Let’s Understand with a Real Example Imagine this HTML: <body> <h1>Hello</h1> <button>Click Me</button> </body> Browser ise internally convert karta hai: Document └── body ├── h1 └── button 👉 Ye pura structure hi DOM hai 🔹 Why DOM is Important? Without DOM: ❌ JavaScript kuch change nahi kar sakta ❌ Website static rahegi With DOM: ✅ Text change kar sakte ho ✅ Elements add/remove kar sakte ho ✅ Events handle kar sakte ho 🔹 Accessing DOM using JavaScript let heading = document.querySelector("h1") console.log(heading) 👉 JavaScript ne HTML element access kar liya 🔹 Changing Content let heading = document.querySelector("h1") heading.innerText = "Welcome to JavaScript" 👉 Screen par text change ho jayega 😎 🔹 Button Click Example let button = document.querySelector("button") button.addEventListener("click", function() { alert("Button Clicked!") }) 👉 User click kare → action trigger hota hai 🔥 Real Life Example Think of a website like a remote-controlled machine 🎮 HTML → structure CSS → design JavaScript (DOM) → control 👉 DOM is the bridge between JavaScript and HTML 🔥 Simple Summary DOM → HTML ka structure JavaScript → DOM ko control karta hai Result → Interactive website 💡 Programming Rule If you can control the DOM, you can control the entire website. If you want to learn JavaScript in a simple and practical way, you can follow these YouTube channels: • Rohit Negi •Hitesh Choudhary (Chai aur Code) 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → Selecting Elements (Next Post) Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
Lately, I’ve been going deeper into JavaScript coercion, and the more I study it, the less random JavaScript feels. A lot of behaviour that looks strange at first starts making sense once you realise that JavaScript is following rules defined in the ECMAScript specification. Recently, I focused on the abstract operations behind conversion, especially: - ToNumber - StringToNumber - ToString - ToPrimitive - OrdinaryToPrimitive One of the biggest takeaways for me is that JavaScript does not just “guess” what to do with values. It follows a defined process depending on the operation being performed. For example: - `"5" - 1` works because subtraction expects numbers. - `Number("")` becomes `0`. - `Number(undefined)` becomes `NaN`. - `ToNumber(BigInt)` throws an error, but `ToString(BigInt)` works. - When an object is involved, JS first tries to extract a primitive value before continuing coercion The part I found especially interesting was object-to-primitive conversion. If JavaScript encounters an object in a coercion context, it first checks for `Symbol.toPrimitive`. If that is not available, it falls back to `OrdinaryToPrimitive`, where the order of calling `toString()` and `valueOf()` depends on the hint being used: - string hint → toString() first - number hint → valueOf() first I also learned more about why string-to-number conversion behaves the way it does: - Number("25") gives 25 - Number(" 25 ") also gives 25 - Number("Infinity") gives Infinity - Number("1_000") gives NaN - Number("10n") gives NaN What is changing my understanding the most is this: - Instead of memorising “weird JavaScript behaviour”, I’m now trying to ask: 1. What operation is being performed? 2. What type of value does that operation expect? 3. Which abstract operation is JavaScript using behind the scenes? That mindset makes the language much easier to reason about. I’ve also been maintaining detailed notes on what I’m learning. If anyone wants to go deeper into these topics, I’ve uploaded them here: GitHub repo: https://lnkd.in/ephuZ-w6 #JavaScript #TypeScript #WebDevelopment #SoftwareEngineering #ECMAScript #100DaysOfCode
To view or add a comment, sign in
-
-
Prototypes & the Prototype Chain If you’re using class in JavaScript, you’re already using prototypes whether you realize it or not. Today was about understanding what that actually means under the hood. What I focused on Prototypes & the chain Every object in JavaScript has an internal link to another object called its prototype. You don’t see it directly, but it’s always there. When you try to access a property, JavaScript follows a simple process: * First, it checks the object itself * If not found, it looks at the object’s prototype * If still not found, it keeps going up the chain * This continues until it either finds the property or reaches null That lookup flow is called the prototype chain. A simple example: ``` function Person(name) { this.name = name; } Person.prototype.sayHello = function () { return "Hello " + this.name; }; const user = new Person("Naim"); console.log(user.sayHello()); ``` Here’s what’s happening: * `user` does not have `sayHello` directly * JavaScript looks at `Person.prototype` * It finds `sayHello` there and executes it That’s the prototype chain in action. Manual inheritance (no class) Built inheritance from scratch using constructor functions to understand how objects can share behavior. ``` function Animal(name) { this.name = name; } Animal.prototype.speak = function () { return this.name + " makes a sound"; }; function Dog(name) { this.name = name; } Dog.prototype = Object.create(Animal.prototype); Dog.prototype.constructor = Dog; const d = new Dog("Rex"); console.log(d.speak()); ``` What’s happening here: * `Dog` doesn’t have `speak` * Its prototype is linked to `Animal.prototype` * So JavaScript finds `speak` there through the chain This is the same mechanism behind class-based inheritance. Modifying prototypes A few behaviors stood out while testing: * Adding a method to a prototype affects all existing instances * Property lookup happens at runtime, not when the object is created * If an object defines its own property, it overrides the prototype (shadowing) Example: ``` Person.prototype.age = 25; console.log(user.age); // 25 user.age = 30; console.log(user.age); // 30 (shadows prototype) ``` Takeaway Prototypes are how JavaScript actually shares behavior between objects. The prototype chain is how JavaScript resolves properties. Once this clicks, things like inheritance, method sharing, and even some common bugs start making a lot more sense. #javascript #webdevelopment #frontend #learninginpublic
To view or add a comment, sign in
-
-
🚀 JavaScript Simplified Series — Day 28 Promises made async code better… But still… something feels messy 😵 👉 Too many .then() 👉 Hard to read 👉 Looks like chaining hell What if async code could look like normal synchronous code? 🤔 🔥 Solution → Async / Await 🔹 The Problem with Promises fetchData() .then(data => { console.log(data) return processData(data) }) .then(result => { console.log(result) }) .catch(err => console.log(err)) 👉 Works… but not clean ❌ 🔹 Async / Await (Cleaner Way) async function handleData() { try { let data = await fetchData() console.log(data) let result = await processData(data) console.log(result) } catch (err) { console.log(err) } } handleData() 👉 Looks simple & readable ✅ 🔍 What is happening? 👉 async → function always returns a promise 👉 await → waits for promise to resolve 🔹 Example function fetchData() { return new Promise(resolve => { setTimeout(() => { resolve("Data received") }, 2000) }) } async function getData() { let data = await fetchData() console.log(data) } getData() 👉 Output: Data received 🔥 Real Life Example Think of cooking 🍳 👉 Order ingredients 👉 Wait for delivery 👉 Then cook With async/await: Step by step… clean and clear 🔥 Simple Summary async → makes function async await → waits for result Result → clean & readable code 💡 Programming Rule Write async code like sync code. Clarity > complexity. If you want to learn JavaScript in a simple and practical way, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling Day 25 → Event Delegation Day 26 → Async JavaScript Day 27 → Promises Day 28 → Async / Await Day 29 → Fetch API (Next Post) Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
🚀 JavaScript Simplified Series — Day 30 JavaScript feels fast… But have you ever wondered 👇 👉 How does it handle multiple tasks at once? 👉 How does async code run without blocking? This is where the **Event Loop** comes in 😎 --- ## 🤯 The Big Confusion JavaScript is **single-threaded** 👉 It can do **one thing at a time** Then how does this work? 👇 ```javascript id="el1" console.log("Start") setTimeout(() => { console.log("Async Task") }, 0) console.log("End") ``` 👉 Output: Start End Async Task Wait… why? 🤔 --- ## 🔥 Behind the Scenes JavaScript has 3 main parts: 👉 Call Stack 👉 Web APIs 👉 Callback Queue --- ## 🔹 Step by Step Flow 1️⃣ `console.log("Start")` → runs first 2️⃣ `setTimeout` → goes to **Web API** 3️⃣ `console.log("End")` → runs next 4️⃣ Callback goes to **Queue** 5️⃣ Event Loop checks → stack empty? 6️⃣ Yes → push callback to stack 👉 Then runs → "Async Task" --- ## 🔍 Visualization ```id="viz1" Call Stack → Executes code Web APIs → Handles async tasks Queue → Stores callbacks Event Loop → Manages everything ``` --- ## 🔥 Real Life Example Think of a **restaurant 🍽️** 👉 Waiter takes order → sends to kitchen 👉 Kitchen prepares food 👉 Meanwhile waiter serves others 👉 When food is ready → serves you 👉 Event Loop = waiter managing tasks --- ## 🔥 Simple Summary JS → single-threaded Async → handled outside Event Loop → manages execution --- ### 💡 Programming Rule **JavaScript is not multi-threaded… but it behaves like it is.** --- If you want to learn JavaScript in a **simple and practical way**, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) --- 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling Day 25 → Event Delegation Day 26 → Async JavaScript Day 27 → Promises Day 28 → Async / Await Day 29 → Fetch API Day 30 → Event Loop Day 31 → Scope (Next Post) --- Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
-
🚀 JavaScript Hoisting 💥 JavaScript Hoisting Explained: Why Your Code Breaks Before It Runs 👉 Hoisting is JavaScript's behavior of moving declarations to top of their scope during execution. 🔹 1. What Gets Hoisted? - var: Hoisted, initialized as undefined - let: Hoisted, not initialized (TDZ) - const: Hoisted, not initialized (TDZ) - function: Fully hoisted 🔹 2. Variable Hoisting (var) console.log(x); var x = 5; 👉 Output: undefined 👉 Behind the scenes: var x; console.log(x); // undefined x = 5; 🔹 3. let & const Hoisting (TDZ) console.log(a); let a = 10; 👉 Output: ReferenceError 👉 Why? Because of Temporal Dead Zone (TDZ) 👉 Variable exists but cannot be accessed before declaration 🔹 4. Function Hoisting ✅ Function Declaration (Fully Hoisted) greet(); function greet(){ console.log("Hello"); } 👉 Works perfectly ❌ Function Expression (Not Fully Hoisted) greet(); var greet = function(){ console.log("Hello"); } 👉 Output: TypeError: greet is not a function 🔹 5. Temporal Dead Zone (TDZ) 👉 Time between: Variable hoisted Variable declared During this time → ❌ cannot access variable { console.log(x); // ❌ Error let x = 5; } 🔹 6. Common Mistakes ❌ Using variables before declaration ❌ Confusing var with let ❌ Assuming all functions behave the same ⭐ Most Important Points ✅ var → hoisted with undefined ✅ let/const → hoisted but in TDZ ✅ Function declarations → fully hoisted ✅ Function expressions → not fully hoisted 🎯 Quick Summary - JavaScript moves declarations up, not values - var → usable before declaration (but undefined) - let/const → cannot use before declaration - Functions → behave differently based on type If this finally made hoisting click for you… 👉 Drop a ❤️ and comment "HOISTED" 👉 Follow Mohd Sharfuddin Khan for more bite-sized dev concepts that actually make sense
To view or add a comment, sign in
-
✨ 𝗪𝗿𝗶𝘁𝗲 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗦𝘁𝗿𝗶𝗻𝗴𝘀 𝗟𝗶𝗸𝗲 𝗔 𝗛𝘂𝗺𝗮𝗻 ⤵️ Template Literals in JavaScript: Write Strings Like a Human ⚡ 🔗 𝗥𝗲𝗮𝗱 𝗵𝗲𝗿𝗲: https://lnkd.in/d_HhAEsM 𝗧𝗼𝗽𝗶𝗰𝘀 𝗰𝗼𝘃𝗲𝗿𝗲𝗱 ✍🏻: ⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺ ⇢ Why string concatenation becomes messy in real apps ⇢ Template literals — the modern way to write strings ⇢ Embedding variables & expressions using ${} ⇢ Multi-line strings without \n headaches ⇢ Before vs After — readability transformation ⇢ Real-world use cases: HTML, logs, queries, error messages ⇢ Tagged templates (advanced but powerful concept) ⇢ How interpolation works under the hood ⇢ Tradeoffs & common mistakes developers make ⇢ Writing cleaner, more readable JavaScript Thanks Hitesh Choudhary Sir & Piyush Garg Sir, and the amazing Chai Aur Code community 🙌 #ChaiAurCode #JavaScript #WebDevelopment #Frontend #Programming #CleanCode #Hashnode
To view or add a comment, sign in
-
How to build a before/after image reveal effect… (Without using JavaScript): 🚀 Ever seen those sliders where you compare two images by dragging? That’s called an image comparison effect, and it’s widely used in: → Photo editing tools → Landing pages → Case studies But here’s the catch: We used to rely heavily on JavaScript for this. --- 💥 What we used before (JavaScript approach): → Track mouse position (`mousemove`) → Calculate width dynamically → Update styles on every frame → Handle drag logic manually Something like this: ```id="jsold1" const container = document.querySelector(".compare"); const afterImage = document.querySelector(".after"); container.addEventListener("mousemove", (e) => { const rect = container.getBoundingClientRect(); const x = e.clientX - rect.left; const percent = (x / rect.width) * 100; afterImage.style.clipPath = `inset(0 ${100 - percent}% 0 0)`; }); ``` 👉 Works… but feels heavy for such a simple UI. --- Now here’s the fun part: We don’t need JavaScript anymore. --- Here’s how to build it using pure CSS: 1️⃣ Stack both images inside a container: The trick is to place one image over the other. ```id="htmlstep1" <div class="compare"> <img src="before.jpg" /> <img src="after.jpg" class="after" /> </div> ``` --- 2️⃣ Make the container relative: This allows the top image to position correctly. ```id="cssstep2" .compare { position: relative; width: 400px; overflow: hidden; } ``` --- 3️⃣ Position the top image: Place it exactly over the first one. ```id="cssstep3" .after { position: absolute; top: 0; left: 0; } ``` --- 4️⃣ Hide it using clip-path: This is where the magic happens. ```id="cssstep4" .after { clip-path: inset(0 100% 0 0); transition: clip-path 0.6s ease; } ``` 👉 This makes the image invisible from the right side. --- 5️⃣ Reveal it on hover: ```id="cssstep5" .compare:hover .after { clip-path: inset(0 0 0 0); } ``` 👉 Now the image smoothly reveals on hover. --- And if you want to go one step ahead, try this: ✨ Show both images at once: ```id="cssstep6" .compare:hover .after { clip-path: inset(0 50% 0 0); } ``` ✨ Add a diagonal reveal: ```id="cssstep7" .after { clip-path: polygon(0 0, 0 0, 0 100%, 0 100%); } .compare:hover .after { clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%); } ``` --- Anyways: CSS is no longer just styling. It’s handling: → Interactions → Animations → UI behavior 👉 Things we used to depend on JavaScript for. And honestly… Sometimes CSS is all you need. #CSS #WebDevelopment #Frontend #UI #UX
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