π Real-World Bug: “Button Click Not Working
π§ The Code:
π§ Step-by-Step Debugging:
π Step 1: Read the error
Open the browser console. You may see something like:
π§© Step 2: Reproduce the bug
Clicking the button does nothing. The alert
doesnβt appear.
π Step 3: Investigate
Check this line:
Now check the HTML:
π Problem: ID is case-sensitive
-
clickme
βclickMe
β Step 4: Fix it
Update the code:
Now clicking the button works. π
π Advanced Debug Tip: DOM Not Ready
If you moved the script to the head section or used defer=false
, this can also cause the error.
Better Approach:
Wrap your code in DOMContentLoaded
:
π‘ Key Lessons from This Debugging Example
Lesson | Why It Matters |
---|---|
ID case sensitivity | JavaScript is case-sensitive |
DOM must be loaded | Always access elements after they exist |
Use console errors | Always check browser dev tools |
Small typo = Big bug | Carefully check spelling & IDs |