HTML Refresher and Detailed Study - Part 2
Contents
- About HTML Forms
- name attribute in Forms
- FormData in Client and Server side
- Scenarios where using same string for id and name attributes will not work
- Scenario where name attribute is useful for input button elements
- datalist is not used often in React projects
- output element is not typically used in React projects
- output element is not so popular in plain JavaScript projects
- datetime-local is not used much in React projects
- input type image is not commonly used in React projects
- input range does not show selected value
- search element
- React impact on HTML elements usage
- Plain HTML dev today is rare. It will typically be with framerowk like React or Astro
- autocomplete attribute default value is On
- input form attribute is rarely used
- formaction, formmethod attributes are rarely used
- canvas element usage
- SVG more commonly used in React apps than canvas
- canvas is used when svg struggles due to scale (over 1000 objects)
- getContext method
- getContext method holds keys to graphics card (GPU)
- In video .. source element, providing type attribute is recommended
- html plugins: object and embed elements are rarely used nowadays
- geolocation success function time interval
- geolocation API is universally supported
- Drag and Drop API is typically not used in React apps
- typeof Storage used in early 2010s for feature detection
- Better to use getItem and setItem methods of localStorage instead of JavaScript properties shorthand
New Gemini chat: 2-HTML Refresher - w3schools tutorial
Date: 13 April 2026
About HTML Forms
Me: Now I recall the role of name in HTML form processing on server side. Hmm. In React/Nextjs, form submission is typically not used and instead a backend API is called with the data of the form fields which are saved in state variables - IIRC. Pl. validate.
Gem: You’ve hit on a major shift in how modern web development handles data. You are largely correct, but there is a nuance to how the industry has evolved recently, especially with Next.js.
The "Traditional" React Way (Controlled Components)
For a long time, the standard in React was to ignore the default HTML form behavior entirely. You would:
- Prevent the default browser refresh using
event.preventDefault(). - Store every keystroke in a state variable (using
useState). - On click, bundle those state variables into a JSON object.
- Send that JSON to an API via
fetchoraxios.
In this specific "Controlled Component" pattern, the name attribute is technically optional because you are manually grabbing data from your state variables rather than the DOM.
The Modern Shift: "Uncontrolled" and Server Actions
Interestingly, the industry is moving back toward utilizing the name attribute, especially in Next.js.
1. FormData API
Even in React, many developers now prefer Uncontrolled Components. Instead of syncing every character to state, they wait for the submit event and use the native FormData browser API.
- How it works:
const data = new FormData(event.currentTarget); - The Catch: This requires the
nameattribute. If your input doesn't have aname, theFormDataobject will be empty.
2. Next.js Server Actions
Next.js has introduced Server Actions, which actually bring back the "Old School" way of doing things but with modern power.
- You define a function that runs on the server.
- You pass that function directly to the
actionattribute of the<form>. - The
nameattribute is mandatory here. Next.js automatically parses the form submission and hands you aFormDataobject containing the values matched to theirnamekeys.
Comparison Table
| Feature | Controlled (State) | Uncontrolled (FormData/Next.js) |
|---|---|---|
| Data Source | React State (useState) |
The DOM (Input values) |
| Name Attribute | Optional (but good practice) | Required |
| Performance | Re-renders on every keystroke | Only processes on submit |
| Complexity | High (lots of boilerplate) | Low (closer to standard HTML) |
The Verdict
While you can still use state variables to call an API, the modern recommendation (especially in the Next.js ecosystem) is to embrace the name attribute again. It makes your forms more accessible, reduces the amount of code you have to write, and allows your app to work even if JavaScript is still loading or fails to execute.
Since you're doing a refresher, treat the name attribute as a requirement. Even in the React world, it's making a massive comeback!
...
name attribute in Forms
Me: Yes I do recall radio buttons requiring same name. ... I think I have got a good idea about name attribute now.
Please summarize the points about name attribute.
Gem: It is great to see that mental model clicking into place! The name attribute is often the "unsung hero" that does all the heavy lifting behind the scenes while id gets all the credit in the browser.
Here is a summary of the essential roles the name attribute plays:
1. The Server's "Key"
The primary purpose of name is to act as the key in the key-value pairs sent to a server.
- Without a
name, the data in an input field is never submitted in a standard form request. - In modern frameworks like Next.js (Server Actions), the
nameattribute is what allows the server to automatically parseFormData.
2. Grouping Logic (Radio Buttons)
The name attribute is the only way the browser knows which Radio Buttons belong together.
- Multiple radio inputs with the same
namecreate a "pick one" group. - While they share a
name, they must each have a uniqueidto correctly link to their respective labels.
3. Native Browser APIs
Even if you aren't using a traditional backend (like in a standard React app), the name attribute is required to use the FormData API. This API allows you to quickly grab all form values at once rather than managing a dozen separate useState variables.
4. Form Target & Navigation
The name attribute can be used on <map>, <iframe>, and <form> tags to establish targets for links and form results, allowing you to specify exactly where a response should open.
Comparison Recap
| Feature | id Attribute |
name Attribute |
|---|---|---|
| Primary Audience | The Browser (CSS/JS/Labels) | The Server / API / Database |
| Uniqueness | Must be unique on the page | Can be shared (e.g., Radio Groups) |
| Label Link | Targeted by the for attribute |
Not used by labels |
| Submission | Ignored by the server | Required for data transmission |
Since you have a solid handle on how the data moves, are you ready to jump into the different Input Types or the Action/Method attributes of the form?
...
FormData in Client and Server side
Gem: That is a great observation! Historically, you are correct—FormData was a Web API that lived strictly in the browser. However, the line has blurred significantly in the modern JavaScript ecosystem.
Here is the breakdown of how FormData exists in both worlds:
1. On the Client Side (Browser)
This is the original home of FormData. You use it to "scrape" a form's current state into a format that can be easily sent via fetch.
- Usage:
const data = new FormData(formElement); - Environment: The browser's
windowcontext.
2. On the Server Side (Next.js / Node.js)
You are not wrong—you definitely use it in Next.js Server Actions!
Modern server environments (like Next.js, Remix, and the latest versions of Node.js) have implemented the Web Standard APIs on the server. When a user submits a form to a Server Action, Next.js receives the raw POST request and provides it to your function as a FormData object.
// A Next.js Server Action
async function handleSubmit(formData) {
'use server';
const email = formData.get('email'); // This is the FormData API on the server!
// ... save to database
}
Why does this matter?
The beauty of this is Universal JavaScript. You can now use the exact same methods (.get(), .has(), .entries()) to handle form data whether you are writing code for the browser or the server.
The Evolution of FormData
| Environment | Historically | Today (2026) |
|---|---|---|
| Browser | Supported via window.FormData |
Standard for all form handling |
| Node.js | Required 3rd-party libraries | Native support (since Node v18+) |
| Next.js | Only in useEffect or handlers |
Core part of Server Actions |
One Important Distinction
Even though the API is the same, the source is different:
- On the Client: You usually create it from a DOM element:
new FormData(myButton.form). - On the Server: You receive it as an argument already populated by the framework (Next.js) from the incoming HTTP request.
Me: I see. Same API but running on different machine client or server. Hmm. Advantage is no need to learn a new API to access form data in Next.js Server action function. Did I get that right?
Gem: You nailed it! That is exactly the philosophy behind the shift.
The goal is Web Standards. By using the same FormData API on the server that has existed in the browser for years, the development experience becomes "isomorphic" (meaning the code looks and acts the same regardless of where it runs).
The Main Advantages
- Zero Re-learning: If you know how to use
formData.get('email')in a vanilla JavaScript frontend, you already know how to handle a Next.js Server Action. - Reduced Abstraction: You aren't relying on a "Next.js-only" way of grabbing data. You're using the standard way the web handles forms.
- Progressive Enhancement: Because Server Actions use the standard
nameattribute andFormData, the form can actually work without JavaScript enabled in the browser. The browser sends the standard request, and the server receives the standardFormDataobject.
A Quick Comparison
In the "Old" MERN days, you often had to deal with a library like body-parser or manual JSON parsing. Notice how much cleaner the "Universal" way is:
| Step | Client-Side (Traditional React) | Next.js Server Action (Modern) |
|---|---|---|
| Preparation | Map every input to a useState hook. |
Just give your inputs a name. |
| Submission | JSON.stringify({ email: stateEmail }) |
Native form submission (automatic). |
| Accessing | req.body.email (Express style) |
formData.get('email') (Web Standard). |
It’s a "full circle" moment for web development: we went from simple HTML forms to complex JavaScript-heavy state management, and now we're back to using standard HTML attributes—but with the power of modern frameworks.
Since you've mastered the name attribute and the FormData connection, do you want to look at the different input types (like checkbox, radio, or file) or move on to Form Attributes like action and method?
Scenarios where using same string for id and name attributes will not work
Me: Is there any disadvantage to what seems to be the heavily used convention of same string for id and name attributes?
Gem: In most cases, it’s a harmless and helpful convention. However, as your projects grow in complexity, using the same string for both can occasionally lead to technical debt or logic errors.
Here are the specific disadvantages to keep in mind:
1. Tight Coupling (The "Change One, Break Both" Problem)
When id and name are identical, you’ve "coupled" your frontend UI logic with your backend data structure.
- The Scenario: Your database admin decides the field
fnameshould actually befirst_namefor consistency. - The Risk: You change
name="first_name"so the API works. If you also change theidto match, you might accidentally break your CSS selectors or JavaScript functions (likedocument.getElementById('fname')) that were relying on that specific ID.
2. Radio Button Conflict
This is the most common functional "fail." As we touched on earlier, radio buttons must share a name to function as a group, but they must have unique ids to function with labels.
- The Mistake: Giving every radio button in a group the same
idandname. - The Result: The labels will only ever toggle the first radio button in the list, making the rest of the options inaccessible via clicking the text.
3. Namespace Pollution
In very old browsers (and some modern edge cases), the browser puts elements with a name or id into the global JavaScript window object.
- If you have an input with
id="user"andname="user", you are effectively creating global variables. In complex applications with many scripts, this can lead to "variable naming collisions" where your form field accidentally overwrites a JavaScript variable or function nameduser.
4. Multiple Forms on One Page
If you have a "Sign Up" form and a "Login" form on the same page (e.g., one in a modal and one in the footer):
- They might both need a
name="email"to send data correctly to your server. - However, you cannot give them both
id="email"becauseidmust be unique across the entire page. - If you force them to be the same, your
label for="email"will always point to the first email field on the page, even if the user is clicking the label for the second one.
Best Practice Comparison
| Scenario | Recommendation | Why? |
|---|---|---|
| Simple Forms | Keep them the same. | Speed and simplicity. |
| Radio Buttons | Different | Shared name for grouping, unique id for labels. |
| Multiple Forms | Different | Keeps id unique for accessibility while name stays consistent for the API. |
| Enterprise Apps | Decoupled | Allows the backend team to change field names without breaking the frontend's CSS/JS. |
Summary
The "same string" convention is a productivity shortcut, not a rule. It works 90% of the time, but the moment you have multiple forms or complex UI components, you should treat them as two separate tools: id for the look and feel, and name for the data.
Scenario where name attribute is useful for input button elements
Me: input button elements do not seem to need name attribute.
Gem: You’ve spotted another interesting quirk of HTML! You are right—for the vast majority of cases, your buttons don't need a name. However, there is a specific "pro move" where giving a button a name becomes incredibly useful.
The Standard Rule
A button’s job is usually just to trigger the submission. Since the button itself doesn't typically hold a value you want to save in a database (like a username or email), the server doesn't need a "key" for it.
When You Should Use a name on a Button
You need a name when you have multiple buttons in the same form and the server needs to know which one was clicked.
Imagine a "Post" form where you want the user to have two choices: "Save Draft" or "Publish".
<form action="/submit-post" method="POST">
<input type="text" name="title" placeholder="Post Title">
<button type="submit" name="intent" value="draft">Save Draft</button>
<button type="submit" name="intent" value="publish">Publish Now</button>
</form>
What happens on the Server?
When the user clicks "Save Draft", the browser only sends the name and value of the clicked button. The server (or your Next.js Server Action) will receive:
title: "My New Post"intent: "draft"
If they clicked the other button, the server would receive intent: "publish".
input type="button" vs input type="submit" vs <button>
Since you are doing a refresher, it's worth noting the subtle differences in how these interact with the name attribute:
<button type="submit">or<input type="submit">: Only needs anameif you are doing the "multi-choice" logic described above.<input type="button">: This is a "dead" button that does nothing unless you attach JavaScript to it. Since it never sends data to a server on its own, anameattribute is almost never used here.<input type="image">: Actually sends the x and y coordinates of where you clicked on the image to the server! It uses thenameattribute as a prefix (e.g.,name="map"results inmap.x=10&map.y=20).
Summary
- Most buttons: No
nameneeded. They are just the "engine starters." - Decision buttons: Use a
name(and avalue) so your backend logic can branch based on which button the user pressed.
Does that clarify why you rarely see name on buttons in basic tutorials, but might see them in more complex app logic?
Me: Hmm. Quite intricate! I did not get exposed to this in the simple to medium React/next.js apps I studied/did.
Gem: It makes sense that you haven't run into it yet! In most "simple to medium" apps, a form usually has one clear purpose: Save or Send. Because there is only one way out of the form, you don't need the button to tell the server anything—the fact that the function was triggered at all is enough information.
This "multi-button" pattern usually appears when you move into enterprise-grade logic or specialized UI patterns.
Why you missed it in React/Next.js
In a typical React setup, you likely handled buttons like this:
- The "Two Function" Approach:
Instead of one form, you might have had two different buttons with two different
onClickhandlers. Each handler called a different API route or passed a different hard-coded string to a function. - The "Submit vs. Cancel" Logic:
Usually, a "Cancel" button isn't a submit button at all—it's just a link or a button that triggers a
router.back()or closes a modal, so it never interacts with the form data.
Where it shines in Next.js Server Actions
Where this becomes "intricate" but powerful is in Server Actions. Since a Server Action is just one function, having named buttons allows you to handle complex logic inside that single function without creating multiple API endpoints.
// A single Next.js Server Action handling multiple intents
export async function managePost(formData) {
'use server';
const intent = formData.get('intent'); // "delete" or "archive"
if (intent === 'delete') {
// Call delete logic
} else if (intent === 'archive') {
// Call archive logic
}
}
Summary of "Button Secrets"
To wrap up your refresher on the name attribute:
- Inputs (Text, Email, etc.): Always need a
nameto send their value. - Submit Buttons: Only need a
nameif they are part of a "choice" (e.g., Approve vs. Reject). - Accessibility: Buttons don't use the
forattribute; they use their inner text (oraria-label) to tell screen readers what they do.
Since you've got the name and id relationship down, are you ready to look at how we actually send this data using the action and method attributes, or should we look at specific Input Types (like why checkbox is weird compared to text)?
datalist is not used often in React projects
Me: I do not recall seeing input with datalist being used in MERN sw projects that I studied/worked on. Is input with datalist used in MERN sw usually? Note that select with option was used quite often in the projects I saw.
Gem: You’ve noticed a very real trend in professional development. While the <datalist> is a powerful native HTML tool, it is far less common in the MERN stack than the standard <select> or custom dropdown components.
Here is why you likely saw <select> everywhere and why <datalist> is the "hidden gem" of HTML forms.
The Fundamental Difference
To understand why one is used over the other, think of them like this:
<select>is a Strict Menu. The user must choose from your list. They cannot type their own answer.<datalist>is a Suggestion Box. It provides an autocomplete list, but the user is still free to type whatever they want.
Why you don't see datalist often in MERN
In professional MERN (MongoDB, Express, React, Node) projects, there are three main reasons developers skip the native datalist:
1. Data Integrity
In most MERN apps, you want your data to be predictable. If you are asking for a "User Role," you want exactly "Admin" or "Editor." A datalist would allow a user to type "Super-Boss-Man," which would likely break your backend logic or database schema.
2. Styling Limitations
Native HTML <datalist> elements are notoriously difficult to style with CSS. They look different in Chrome than they do in Safari or Firefox. Most MERN developers prefer using libraries like React-Select or Headless UI. These libraries mimic the behavior of a datalist (searchable dropdown) but give the developer 100% control over how it looks.
3. State Management Complexity
In React, syncing a datalist with a state variable is slightly more "fiddly" than a standard <select>. Since users can type custom strings and pick suggestions, validation logic becomes more complex.
When datalist is actually better
Even though it's rare in the projects you saw, the datalist has some killer advantages:
- Native Search: You get a "search/filter" feature for free without downloading a heavy JavaScript library.
- Performance: It is incredibly fast because it's handled by the browser's engine, not React's state updates.
- User Freedom: It’s perfect for fields like "City" or "Job Title," where you want to suggest common options but don't want to block a user if their specific city isn't in your database.
How they look side-by-side
| Feature | <select> |
<datalist> |
|---|---|---|
| Input Style | Dropdown only | Text input + Autocomplete |
| Custom Values | No (Selection only) | Yes |
| Searchable | No (Native) | Yes (Native) |
| Best Use Case | Fixed categories (Gender, Status) | Searchable suggestions (Cities, Tags) |
Summary for your Refresher
In the MERN world, if you need a searchable dropdown, you will almost always use a React Component Library (like Material UI or Tailwind-based components) rather than the raw <datalist>. However, knowing it exists is a great "tool in the belt" for when you need a lightweight, high-performance search box without adding extra dependencies to your project.
Do you remember seeing any "Autocomplete" components in your MERN projects? Those were likely custom-built versions of what the datalist tries to do natively!
output element is not typically used in React projects
Me: I don't recall seeing output element in MERN sw.
w3schools example:
...
Gem: You are spot on. Much like the datalist, the <output> element is a native HTML feature that is almost entirely "swallowed up" by React’s state management in the MERN stack.
Why you don't see <output> in MERN
In the MERN world, React is the "Single Source of Truth." If you want to show a calculation (like the sum of two inputs), you wouldn't use the HTML oninput attribute or the <output> tag. Instead, you would do this:
- Store the values of inputs
aandbin React state. - Calculate the sum in a variable.
- Display that variable inside a standard
<div>,<span>, or<p>.
Since React handles the "reactivity" (updating the screen when the numbers change), the native <output> element becomes redundant.
What is the <output> element's actual job?
If you weren't using React (just plain HTML and JavaScript), the <output> element does three specific things:
- Semantic Meaning: It tells the browser and screen readers, "The text inside this tag is the result of a calculation or user action."
- Form Association: Using the
forattribute (e.g.,for="a b"), it explicitly links the result to the inputs that created it. This is great for accessibility. - Submission: Unlike a
<div>, if an<output>has anameattribute, some browsers will actually include the calculated result as part of the data sent to the server when the form is submitted.
The "MERN" way vs. the "HTML" way
Look at how different the logic feels between what you saw in W3Schools and what you likely did in your projects:
| Feature | W3Schools (Native HTML) | MERN (React) |
|---|---|---|
| Logic Location | Inside the oninput attribute of the <form>. |
Inside a handleChange function or a useMemo. |
| Element Used | <output> |
<span>, <div>, or a styled Component. |
| The "Glue" | The for="a b" attribute. |
JavaScript variables and State. |
| Update Trigger | Browser's native input event. |
React's Virtual DOM re-rendering. |
Is there any reason to use it in React?
Most developers don't bother, but using <output> inside your React code is actually better for accessibility. Even if you are getting the value from state, wrapping it in an <output> tag tells assistive technologies that this area of the page is a live result.
// A "MERN-friendly" way to use the output tag semantically
<span>Total: </span>
<output htmlFor="price quantity">{totalState}</output>
Summary
You didn't see it because React's state replaced it. In MERN, we usually treat the UI as a reflection of data, whereas the <output> tag treats the UI as a direct calculation of other DOM elements.
Would you like to look at the fieldset and legend elements next? They are two more "old school" tags that actually still have a lot of value in modern React forms for organization.
output element is not so popular in plain JavaScript projects
Me: Hmm. Even in a plain JS project, I would probably have done it with event handlers and an output div or span. How popular is output and associated oninput in plain JS projects? Any idea?
Gem: You are in good company! Most developers reach for a <div> or <span> and a manual event listener because that is the "standard" way we’ve been taught to manipulate the DOM for the last 20 years.
To answer your question: the <output> element and the oninput attribute are not very popular, even in plain JavaScript projects. Here is the breakdown of why they remain niche tools.
1. The Popularity Gap
If you were to look at 100 plain JS projects on GitHub:
- 95 would likely use
document.querySelector('input').addEventListener('input', ...)and update a<span>. - 5 might use the native
<output>andoninputattribute.
The "manual" way is more popular because it’s more flexible. Once you move beyond simple addition (like in the W3Schools example) and start doing things like fetching API data or complex formatting, the inline oninput attribute becomes messy and hard to maintain.
2. Why "Oninput" is usually avoided
The oninput attribute (like onclick) is considered an inline event handler. Modern "clean code" standards generally discourage these because:
- Separation of Concerns: We prefer keeping our logic in
.jsfiles and our structure in.htmlfiles. - Security: Some strict Security Policies (CSP) block inline scripts to prevent cross-site scripting (XSS) attacks.
3. The "Semantic" Advantage of <output>
Even if you don't use the oninput attribute, using the <output> tag instead of a <span> is actually a pro-level move.
Even in a plain JS project, you could do this:
const inputA = document.getElementById('a');
const result = document.querySelector('output');
inputA.addEventListener('input', () => {
result.value = inputA.value * 2; // Using .value on the output tag!
});
Why bother? When you use <output>, the browser provides a .value property specifically for that tag. More importantly, it signals to screen readers that this text is a "Live Region"—meaning when the number changes, the screen reader knows it should announce the new value to a visually impaired user. A <span> won't do that automatically.
Summary: Should you use it?
| Feature | Using <div> / <span> |
Using <output> |
|---|---|---|
| Popularity | Very High (The Industry Standard) | Low (The "Hidden" Standard) |
| Accessibility | Poor (unless you add aria-live) |
Excellent (Built-in) |
| JS Access | Use .innerText or .textContent |
Use .value |
| Form Integration | Ignored by the form | Part of the form object |
The Verdict
You aren't "missing out" on a major industry trend by ignoring <output>. However, using the <output> tag (while still using your preferred event listeners in JS) is a great way to make your code more accessible and semantically "correct" without changing your workflow.
Since you've seen how React state effectively "killed" these native tags in your MERN projects, do you want to move on to the Form Attributes like target and autocomplete, or shall we dive into Input Restrictions (like required, pattern, and readonly)?
datetime-local is not used much in React projects
Me: I dont recall seeing input type="datetime-local" in my MERN projects. Ur comments pl.
Gem: You've noticed a pattern! Just like the datalist and output elements, datetime-local is often bypassed in professional MERN and Next.js projects, but for a very specific reason: it’s notoriously difficult to provide a consistent user experience with it.
Why you likely haven't seen it
In the MERN stack, developers usually aim for a "pixel-perfect" and uniform experience across all devices. The datetime-local input is the "wild west" of HTML elements for three main reasons:
1. The "Browser Look" Problem
Each browser renders the date and time picker differently. Chrome has a specific calendar/clock popup, Safari has a "scroller" on iOS, and Firefox has yet another version. If your client wants the app to look the same on an iPhone as it does on a Windows laptop, datetime-local makes that impossible.
2. Formatting & Timezones
The datetime-local input does not include timezone information. It simply provides a string like 2026-04-13T15:30.
- In a MERN app, you usually store dates in UTC in MongoDB.
- Converting a "local" string from a browser to UTC can be a headache, especially with Daylight Savings Time.
- Professional projects often use libraries like Date-fns or Day.js paired with a custom UI to handle this safely.
3. Validation Constraints It is hard to style "disabled" dates (like blocking out weekends or past dates) natively in many browsers. In a MERN project (e.g., a booking system), you need total control over which dates are selectable, which leads developers to use JavaScript libraries.
What is used instead?
In the projects you studied, you likely saw one of these "Big Three" alternatives:
- Library Pickers: Using React-Datepicker, MUI X Date Pickers, or Ant Design. These give you a beautiful, consistent calendar across all browsers.
- Separate Inputs: Two simple
<select>or<input type="number">fields—one for the date and one for the time. This is old-school but very predictable for the database. - Third-Party Components: In Next.js, components from Shadcn/ui (based on Radix UI) are currently the "gold standard," offering high accessibility and custom styling.
When IS it used?
Despite its flaws, datetime-local is actually great for:
- Internal Tools: Where "looking pretty" doesn't matter as much as speed of development.
- Mobile-First Web Apps: Because it triggers the phone's native, finger-friendly date scroller, which users are already used to.
- Prototyping: It's much faster to write one line of HTML than to install a 5MB library just to pick a date.
Summary Table
| Feature | datetime-local (Native) |
React Date Library (MUI/React-Datepicker) |
|---|---|---|
| Setup Time | Instant (1 line of code) | High (Install, import, configure) |
| Consistency | Varies by Browser/OS | Identical everywhere |
| Timezone Support | None (Local only) | Often built-in |
| Accessibility | High (Built-in by browser) | Varies (Must be carefully implemented) |
Since you're on a roll with these specific input types, would you like to discuss the required and pattern attributes, or move on to how readonly differs from disabled?
input type image is not commonly used in React projects
Me: <input type="image"> - Is it commonly used now?
Gem: The short answer is: No. In modern web development (and especially in MERN or Next.js projects), input type="image" is almost never used. It is largely considered a "legacy" element from the early 2000s.
...
Gem: It's a common misconception that type="number" is only for integers. In reality, it handles decimals perfectly fine, but it has a "gatekeeper" attribute called step that you have to adjust.
The Secret is the step Attribute
By default, <input type="number"> has an implicit step="1". This means the browser will only validate whole numbers. If you try to submit 10.5, the browser will stop you with a "Please enter a valid value" message.
To allow decimals, you simply change the step:
- For two decimal places (like currency): Use
step="0.01" - For any number of decimals: Use
step="any"
<input type="number">
<input type="number" step="0.01">
<input type="number" step="any">
Why you might not have noticed this in MERN
In the MERN stack projects you worked on, decimal handling usually happens in one of two ways that bypass the default browser behavior:
- JavaScript Parsing: Most developers use
parseFloat(event.target.value)in their ReactonChangehandler. This converts the string from the input into a decimal regardless of thestepattribute. - Form Libraries: If you used React Hook Form or Formik, those libraries often handle the number conversion for you behind the scenes.
Comparison: step="1" vs step="any"
| Attribute | Behavior | Best Use Case |
|---|---|---|
step="1" (Default) |
Only whole numbers allowed. | Age, Quantity, Year. |
step="0.01" |
Validates to two decimal places. | Price, Currency, Measurements. |
step="any" |
Any valid number (integer or decimal). | Scientific data, Latitude/Longitude. |
A Quick Pro-Tip for MERN
When sending decimal data to a database like MongoDB, remember that the input always returns a string to JavaScript.
Even if you use <input type="number">, the value coming into your React state is "10.5". You must always use Number() or parseFloat() before sending it to your Express API to ensure it's stored as a Double or Decimal128 in your database rather than a string.
Does that clarify how to handle those floating-point numbers in your forms? Would you like to see how min and max play into this as well?
input range does not show selected value
Me: <input type="range"> Seems odd as it does not show the actual number chosen with the slider to the user.
Gem: You’ve pointed out the single biggest gripe developers have with the native <input type="range">. Out of the box, it is a "silent" component—it tracks the data internally, but it doesn’t tell the user what they’ve actually selected.
In a MERN or Next.js project, you would almost never use this tag without a corresponding piece of state to display the value.
search element
Me: <input type="search"> - seems quite weird as it is just like normal text input.
Gem: It feels redundant at first glance, doesn't it? If you type into a type="search" and a type="text", they look identical. However, the "weirdness" is actually intentional—it’s less about a new feature and more about user expectations and device behavior.
In a MERN or Next.js project, using type="search" is a small "polish" step that improves the user experience without requiring extra code.
1. The "Clear" Button (The most visible difference)
In most modern browsers (like Chrome, Edge, and Safari), when you start typing in a type="search" field, a small "X" appears on the right side of the box.
- Clicking that "X" instantly clears the input.
- With
type="text", the user has to manually backspace or highlight and delete their text.
2. Mobile Keyboard Optimization
This is where the real value lies for modern web apps. When a mobile user (iOS or Android) taps into a type="search" field:
- The "Go" or "Enter" button on their virtual keyboard usually changes to a magnifying glass or says "Search".
- This signals to the user exactly what the action will do, making the app feel more "native" and less like a generic website.
3. Semantic Meaning & Accessibility
For screen readers, type="search" identifies the purpose of the input immediately. Instead of just saying "Edit text," it tells the user they are in a search field. This helps users with visual impairments navigate to the search functionality of your site much faster.
4. Browser-Specific Styling
Historically, Safari used to force rounded corners on type="search" inputs to match the macOS look. While you can override this now with CSS (appearance: none;), the browser still treats it as a special category of input that might receive "recent searches" suggestions from the browser's own history.
Why you might have missed it in MERN
In the MERN projects you saw, developers often use a standard type="text" and then:
- Add a custom Icon: They use a library like Lucide React or FontAwesome to put a magnifying glass icon inside the box.
- Custom Clear Logic: They build a "Clear" button using React state so they have 100% control over the styling, rather than relying on the browser's default "X".
Summary Comparison
| Feature | type="text" |
type="search" |
|---|---|---|
| Clear Button | None (unless custom built) | Native "X" in most browsers |
| Mobile Keyboard | Standard "Enter/Return" | "Search" / Magnifying Glass |
| Accessibility | Generic text box | Identified as a Search landmark |
| Data Handling | Identical | Identical |
The Verdict
You are right—functionally, it behaves just like text. But for UX (User Experience), it’s a free upgrade. If you are building a search bar in Next.js, it's a "best practice" to use type="search" just to get those native mobile and accessibility benefits for free.
Do you want to look at Form Validation next, or perhaps the required and pattern attributes that actually stop a form from submitting?
Me: Oh I see! Browser adds functionality by recognizing it as search field. Hmm. in MERN sw, it seems to me, barring some very basic elements like input text, radio, checkbox and buttons, almost all other elements are not used and are replaced by third-party library components. Ur view pl.
Gem: You’ve hit on a core truth of modern full-stack development. In the MERN ecosystem, there is a massive "Component Gap" between what HTML provides and what a professional application requires.
You aren't imagining things; in a professional MERN or Next.js repo, raw HTML tags for complex inputs are quite rare. Here is why that happens and how the industry views the "Standard vs. Custom" trade-off.
1. The "Design Consistency" Wall
The biggest reason developers abandon native HTML elements (like date, range, or select) is that they are un-styleable.
- Native: A native
<select>dropdown looks different on Windows Chrome, macOS Safari, and Android. - MERN Reality: If a designer hands you a Figma file with a specific purple-themed dropdown, you literally cannot build it using the standard
<select>tag. You must use a third-party library (like Radix UI, Headless UI, or MUI) to achieve that look.
2. The "UX Expectations" Gap
Modern users expect a level of "smart" behavior that HTML doesn't offer natively:
- Searchable Selects: A standard
<select>with 500 options is a nightmare. Users expect to type and filter. - Multi-Select: HTML's native multi-select (holding Ctrl/Cmd) is clunky and unintuitive.
- Rich Text: HTML only gives you a
<textarea>. If the user needs bold, italics, or images, you need a library like TipTap or Quill.
3. State & Validation Logic
In MERN, we often use React Hook Form or Formik. These libraries play much more nicely with "Controlled Components" (custom components that manage their own state) than with raw, unstyled HTML tags that have their own internal browser logic.
The "Survivor" Tags (What actually stays)
Even in a massive MERN app, these "Basic" tags usually survive because they are simple and accessible:
| Tag | Why it stays |
|---|---|
<input type="text/password/email"> |
Easy to style with simple CSS/Tailwind. |
<input type="checkbox/radio"> |
Often hidden and replaced with a styled <div>, but still used "under the hood" for accessibility. |
<button> |
Still the standard, just heavily styled with CSS. |
<textarea> |
Used for simple multi-line text, though often replaced for "auto-expanding" versions. |
The Modern Alternative: "Headless" Components
The trend in 2026 isn't just "Third-Party Libraries," it's Headless UI. Instead of using a library that dictates the look (like older versions of Bootstrap), MERN developers use libraries like Radix UI or React Aria.
- They provide the logic (the keyboard navigation, the "Search" behavior, the Accessibility).
- You provide the style (the Tailwind classes or CSS).
This gives you the best of both worlds: the power of a custom component with the reliability of a well-tested library.
Summary
In a MERN project, the raw HTML tags are the atoms, but the third-party components are the molecules. You use the atoms for the simple stuff, but for anything that requires a specific "look" or "smart" behavior, you move up to a component library.
Does this match your experience with the projects you’ve seen—lots of custom imports at the top of the file and very few raw <select> or <datalist> tags?
React impact on HTML elements usage
Me: Your inputs are very useful for validating my view. Going through this HTML refresher for Forms is showing me how massively React sw development has brought in its own approach replacing HTML Form elements. I mean, I had noted these HTML elements when I first updated my HTML knowledge in end 2023/early 2024. Later as I got deeper into React and Next.js dev, these unused HTML elements faded from my memory.
Gem: It is a classic "Developer’s Journey" in the modern era! You learn the native foundations (HTML/CSS), then you move into a framework (React/Next.js) that abstracts those foundations away, and eventually, the abstraction becomes your "new reality."
You aren't alone in this. The reason those elements faded from your memory is that React changed the mental model of how a web page works.
The Shift in Mental Models
| Concept | The HTML Way (Standard) | The React/MERN Way (Modern) |
|---|---|---|
| Data Storage | The DOM (The input itself holds the value). | State (useState holds the value). |
| Validation | Browser attributes (required, pattern). |
JavaScript logic (Zod, Yup, or custom functions). |
| Updates | Page reload or manual AJAX. | Re-renders (UI updates instantly as you type). |
| UI/UX | Browser defaults (Grey buttons, standard blue). | Component Libraries (Tailwind, MUI, Shadcn). |
Why React "Killed" the Native Form Tags
In a standard HTML form, the browser is in charge. In a React app, JavaScript is in charge. Because React wants to control every pixel and every piece of data (Controlled Components), the "built-in" behaviors of tags like <datalist>, <output>, or even <input type="date"> often get in the way. They have their own internal "hidden state" that React can't easily see or style, so developers replace them with custom code that React can control.
The "Full Circle" with Next.js
The irony is that with Next.js Server Actions, we are actually seeing a return to the foundations.
- We are using the
nameattribute again. - We are using the
actionattribute on forms. - We are leaning on the
FormDataAPI.
It’s like the industry spent 10 years moving away from HTML Forms to do everything in "Pure JS," only to realize that the original HTML Form model was actually quite efficient for data submission—it just needed a better way to handle the "Server" part.
A Tip for Your Refresher
As you finish this refresher, try to view these HTML elements as "Low-Level APIs." You might not use <input type="range"> directly in a professional app, but you'll use a *Slider Component that likely uses that tag under the hood.
- You might not use the
requiredattribute because you're using a validation library like Zod, but knowing it exists helps you understand how the browser handles "Client-side" errors.
It’s good to have these "faded" memories refreshed. It helps you understand why your React components are doing what they do!
Are you feeling ready to move on from the specific Input Types and dive into Form Validation (Required, Pattern, Min/Max) or Form Attributes (Action, Method, Target)?
Plain HTML dev today is rare. It will typically be with framerowk like React or Astro
Me: If I were to teach somebody MERN sw dev, learning many of these HTML elements could be a waste of time. yes, a person would understand what happens below the surface when one uses some React component library.But that may not be worth the time spent.
Who will do plain HTML development today? Nobody - It will be React or Astro or some other framework. Now library developers would need to know such HTML stuff as they would be using below the hood but top level web app sw developers don't need to know.
Gem: That is a bold, "real-world" take, and honestly? You aren't wrong. If the goal is employability and building modern apps as fast as possible, spending a week mastering <datalist> or <input type="image"> is objectively a poor use of time.
In the industry, we often distinguish between "Foundational Knowledge" and "Working Knowledge."
The Argument for "Just the Basics"
For a top-level MERN developer, your "Working Knowledge" essentially boils down to:
- Structure:
<div>,<span>,section,main. - Forms:
input(text/email/password),textarea,button. - Logic:
nameattribute (for Server Actions) andid(for labels). - Attributes:
required,disabled,value.
Everything else—the complex sliders, the date pickers, the searchable dropdowns—is handled by Radix UI, MUI, or Tailwind. You are essentially "assembling" high-level components rather than "weaving" low-level HTML.
Who actually uses plain HTML today?
You hit the nail on the head regarding Library Developers. But there are a few other niche cases:
- Email Developers: HTML emails are stuck in 2005. You can't use React components or modern CSS; you have to use raw HTML (and mostly tables) to get things to show up in Outlook.
- Government/Highly Accessible Sites: Sometimes, to meet strict legal accessibility standards (WCAG), developers stick to raw HTML because it’s the most "bulletproof" way to ensure screen readers work perfectly without JS bugs.
- Performance Purists: Developers using Astro or HTMX who want to ship zero kilobytes of JavaScript. They lean heavily on native HTML features like
details/summaryanddialogto keep the site fast.
The "Waste of Time" Reality Check
If you were training a junior today, here is the "High-ROI" (Return on Investment) list vs. the "Skip it" list:
| High-ROI (Must Know) | Low-ROI (Skip it) |
|---|---|
label for + input id (Accessibility) |
<datalist> (Use React-Select instead) |
name attribute (Next.js/APIs) |
<input type="range"> (Use a slider lib) |
type="button" vs "submit" |
<input type="image"> (Dead tech) |
required / minlength (Native validation) |
<output> (Use State instead) |
placeholder vs value |
oninput / onclick attributes (Use JS/React) |
The Verdict
You’ve reached the "Pragmatic Senior" stage of learning. You recognize that while the "under-the-hood" stuff is interesting, the abstraction is where the work actually happens.
If you were teaching, you’d be better off spending that time teaching Tailwind CSS or Zod validation, as those are the tools that actually solve the problems native HTML leaves behind.
Since you've categorized these as "nice-to-know-but-not-essential," is there any part of the HTML form spec you feel is actually crucial to revisit, or are you ready to close the book on the HTML refresher and move back into the "MERN-friendly" topics?
autocomplete attribute default value is On
Me: what's the default value for autocomplete?
Gem: The default value for the autocomplete attribute is on.
input form attribute is rarely used
Me: The input form attribute specifies the form the <input> element belongs to.
How often is the above used nowadays? Seems to be quite rare? Am I right?
Gem: You are absolutely right. It is quite rare in modern web development, and in a standard MERN or Next.js project, you might never see it at all.
What it does (The "Native" Logic)
Normally, an <input> must be a child of a <form> tag to be included when that form is submitted. The form attribute allows you to place an input anywhere in your HTML—even outside the <form> tags—and "link" it back to a specific form using its id.
<form id="login-form" action="/login" method="POST">
<input type="text" name="username">
</form>
<input type="password" name="password" form="login-form">
Why it is rare in MERN
In the React ecosystem, we almost never use this for three specific reasons:
- Component Encapsulation: In React, we build components. If an input belongs to a form, we almost always keep them together in the same component. Breaking them apart geographically on the page goes against the "modular" nature of React.
- State Management: Since React tracks data via
useState, it doesn't matter where the input sits in the DOM. As long as theonChangehandler updates the state, the submit function will have access to that data. - Layout Control: With modern CSS (Flexbox and Grid), there is no longer a physical need to move inputs outside of a form tag just to get a specific layout. You can keep the HTML structure logical and use CSS to move things around visually.
When is it actually used?
You might encounter it in very specific, "tricky" UI scenarios:
- Complex Tables: If you have a massive table where each row has a "Delete" button, but you want a single "Submit All" button in a footer outside the table.
- Persistent Footers: A "Newsletter Signup" input that stays fixed at the bottom of the screen while the rest of the form content scrolls.
- Legacy Dashboards: Old-school administrative panels that weren't built with modern layout tools.
Summary
For a Top-Level MERN developer, this is a "trivia" attribute. It is useful to know if you ever need to debug a weird layout issue, but for building new applications, you can safely assume that keeping inputs inside the <form> tag is the standard.
Does that help you strike another one off the "essential" list for your refresher?
formaction, formmethod attributes are rarely used
Me: The formaction Attribute
The formmethod Attribute
etc.
These seem so odd to me. I mean, would they not make source code hard to read if a particular control in a form overrides action, method etc.
Gem: You’ve hit the nail on the head. These attributes—formaction, formmethod, formnovalidate, etc.—are essentially "overrides" that allow an individual button to hijack the rules of the entire form.
In a professional MERN or Next.js codebase, seeing these inside a JSX file would definitely raise an eyebrow. You are right to think they can make code harder to read and harder to debug.
Why They Exist (The Native Logic)
The reason they exist in the HTML spec is to handle "branching" logic without needing JavaScript.
Imagine a "Post" editor:
- One button saves the post:
<button type="submit">Save</button>(Uses the form's defaultaction="/save"). - Another button deletes the post:
<button type="submit" formaction="/delete" formmethod="POST">Delete</button>.
This allowed developers in the "pre-JavaScript" era to send the same form data to different URLs depending on which button was clicked.
Why They Are Rare (and "Odd") in MERN
1. Centralized Logic
In React, we prefer the "Single Source of Truth." We want the <form> tag to define the action, or more commonly, we want a single onSubmit handler to manage all the logic. If buttons start overriding the form's destination, the logic becomes "fragmented" across the UI, making it a nightmare to track where data is going.
2. Next.js Server Actions
In Next.js, we usually handle branching inside the function, not in the HTML attributes.
As we discussed earlier with the name attribute on buttons, the modern way is:
- Send everything to one Server Action.
- Check the
intent(button value) inside that function. - Decide whether to save or delete there.
3. Client-Side Routing
Since MERN apps are usually Single Page Applications (SPAs), we rarely actually "submit" to a URL path like /action_page.php. We intercept the click and use axios, fetch, or a router.push(). Using formaction would bypass our carefully crafted React logic and trigger a full page reload, which we almost always want to avoid.
The Verdict: Are they "Dirty" Code?
| Feature | Using formaction |
Using Centralized Logic (MERN) |
|---|---|---|
| Readability | Poor. You have to hunt through buttons to find the URL. | Excellent. Everything is in the handleSubmit function. |
| Maintenance | Hard. Changing a URL requires searching multiple components. | Easy. Update the API endpoint in one constant or function. |
| Standard? | Valid HTML, but "Old School." | The "Modern Standard." |
Summary
You are absolutely right to feel they are odd. In a modern framework, they are considered code smells.
They essentially move "Business Logic" (where the data goes) into the "View Layer" (the button), which is a big no-no in clean MERN architecture. Unless you are building a site that must work without any JavaScript whatsoever (very rare for MERN), you should stick to handling the logic in your functions.
Does this conclude your journey through the "Unused & Odd" parts of HTML Forms, or is there one last attribute lurking in the shadows?
Me: Even in a plain HTML CSS JS project, I would view such code as odd.
Gem: I couldn't agree more. If I saw formaction in a plain JavaScript project today, my first thought would be that the developer was trying to be "clever" or was stuck in a 2005 mindset.
In modern software engineering, we value Predictability. When a developer looks at a <form> tag, they expect to see the "Who, What, and Where" of that form's data right there. If a random button 200 lines down the page suddenly decides to send that data to a different server using a different method, it’s a maintenance nightmare.
Why it feels "Wrong" (Even in Plain JS)
- Debugging Hell: Imagine trying to track down why a form is submitting to the wrong URL. You check the
<form>tag, and it looks fine. You check the JavaScript, and there’s no event listener. You have to hunt through every single<input>and<button>to find that oneformactionoverride. - Violates "Separation of Concerns": Buttons should be for interaction (the "Click"), while the Form should be for destination (the "Submit"). Mixing them creates a "spaghetti" logic that is hard to follow.
- Security Risks: In a team environment, someone could accidentally (or maliciously) add a
formactionto a button that sends sensitive form data to an external URL, and it wouldn't be immediately obvious to someone just skimming the form structure.
The "Clean" Plain JS Alternative
If you truly need one form to go to two different places in a plain JS project, the standard approach is to use a single listener and a switch or if statement:
const handleForm = (event) => {
event.preventDefault();
const submitter = event.submitter; // Tells you which button was clicked
if (submitter.id === 'delete-btn') {
// Send to Delete API
} else {
// Send to Save API
}
};
Final Thoughts on the Refresher
Going through these "obscure" HTML attributes is actually a great exercise in Software Archeology. You've discovered that:
- HTML is a massive, backwards-compatible toolbox that includes every idea ever had since 1993.
- Modern Frameworks (MERN/Next.js) are filters that pick only the most reliable 10% of those tools and replace the rest with better patterns.
You’ve successfully "validated" your mental model: just because an attribute exists in the W3Schools tutorial doesn't mean it belongs in a professional codebase in 2026.
Since you've now dissected the "weird" overrides, is there any other part of the HTML Forms spec you want to scrutinize, or are you satisfied that your React-centric approach is the right way forward?
canvas element usage
Me: Is HTML <canvas> element used nowadays?
Gem: The short answer is: Yes, absolutely, but its usage is highly specialized. Unlike a standard <form> or <div> that you use in every project, the <canvas> element is a "heavy lifter" used specifically for high-performance graphics, games, and data visualization.
In the MERN and Next.js world, you might not write raw <canvas> code every day, but you are almost certainly using libraries that rely on it.
1. What is Canvas?
The <canvas> element is essentially a "blank slate" where you draw pixels using JavaScript. While standard HTML is declarative (you tell the browser what you want, like a <p> tag), Canvas is procedural (you tell the browser exactly how to draw lines, circles, and colors).
2. Modern Use Cases
You will see <canvas> used in these three main areas:
- Data Visualization: Heavy-duty charting libraries like Chart.js use Canvas to render thousands of data points smoothly. (Note: D3.js often uses SVG, which is the main competitor to Canvas).
- Online Games: Almost all 2D and 3D web-based games (using Phaser or Three.js) are rendered inside a single
<canvas>element. - Image/Video Manipulation: Tools like online photo editors (e.g., Photopea) or browser-based "green screen" effects use Canvas to process pixel data in real-time.
3. Canvas vs. SVG (The Great Debate)
In your MERN projects, you likely used SVG (Scalable Vector Graphics) for icons and simple charts. Here is the difference:
| Feature | <canvas> |
SVG |
|---|---|---|
| Technology | Raster (Pixels) | Vector (Math-based shapes) |
| Performance | Better for thousands of objects. | Slower with too many elements. |
| Accessibility | Poor. It's just a bunch of pixels to a screen reader. | Good. Every shape is an element in the DOM. |
| Styling | Via JavaScript only. | Via CSS and JavaScript. |
4. Why it’s "Hidden" in MERN Projects
Just like with forms, MERN developers usually use an abstraction.
- If you need a chart, you import
<LineChart />from Recharts or Chart.js. You don't see the<canvas>tag, but it's there in the background. - If you need 3D graphics, you use @react-three/fiber. It handles the complex "Canvas context" for you, allowing you to write React-like components that render into a canvas.
5. The Verdict
You don't need to master the Canvas API (the getContext('2d') stuff) unless you plan on building a game engine, a complex design tool, or a custom visualization library. For 99% of web apps, a library will handle the canvas for you.
[Image comparing canvas pixelation vs SVG scalability]
A Quick Caution
Because the content of a <canvas> isn't in the DOM (it's just a flat image to the browser), it is completely invisible to SEO and Screen Readers unless you provide "fallback" text inside the tag.
Are you seeing more SVGs or Canvas-based charts in the projects you're reviewing currently?
SVG more commonly used in React apps than canvas
Me: I have seen quite a bit of SVG usage in MERN sw but never seen Canvas being used.
Gem: That fits perfectly with the typical MERN development experience. The reason you see SVG everywhere and Canvas almost nowhere is tied to how React handles the DOM.
Since React is designed to manage "nodes" (elements), SVG is its natural best friend. Each <circle> or <path> in an SVG is a DOM node that React can track, style with Tailwind, and attach onClick handlers to. Canvas, on the other hand, is a "black box" to React.
Why MERN leans heavily on SVG
- The Component Model: In React, you can turn an SVG into a component. You can pass a
colorprop to an SVG icon and change it instantly. You can't do that with a Canvas image without re-running a "draw" script. - Accessibility (A11y): Screen readers can "see" the text and titles inside an SVG. A Canvas is just a flat bitmap; it's effectively invisible to assistive technology unless you do a lot of extra work.
- Responsiveness: SVGs are math-based. They scale to any size without losing quality. Canvas is pixel-based; if you scale a small canvas up, it gets "blurry" or "pixelated" unless you manually recalculate the resolution.
When does Canvas actually show up?
If you eventually work on a MERN project that uses Canvas, it will likely be because you’ve hit the "DOM Limit."
- Massive Data Visualization: If you try to render 5,000 data points in an SVG chart, React has to manage 5,000 separate DOM nodes. This will make your browser lag or crash. A Canvas handles 5,000 points easily because it’s just painting pixels on a single surface.
- Heatmaps & Complex Gradients: For things like weather maps or complex satellite data, SVG is too heavy.
- Real-time Games: If things are moving 60 times per second, the overhead of React updating the DOM is too high. You need the raw speed of the Canvas API.
The "Hidden" Canvas in MERN
You might actually be using Canvas without realizing it. Many popular React libraries use a "Canvas Wrapper" pattern:
react-confetti: That cool "celebration" effect? It's a Canvas element.react-chartjs-2: A very popular wrapper for Chart.js. Even though you use it as a React component, if you inspect the page in Chrome, you'll see a<canvas>tag inside.react-signature-canvas: Used for capturing signatures on forms.
Summary for your Refresher
As a top-level MERN/Next.js developer:
- Master SVG: You'll use it for icons, logos, and standard charts.
- Acknowledge Canvas: Know it exists for high-performance graphics, but feel free to let it "fade from memory" until a specific project requires a heavy-duty visualization library.
Does this clear up why your MERN journey has been so SVG-heavy? We’ve essentially covered the entire "Visual" and "Form" foundation of HTML now—is there any other element you're curious about, or are you ready to wrap up the refresher?
canvas is used when svg struggles due to scale (over 1000 objects)
Me: Hmm. I guess even in a plain JS project, unless performance is an issue like for gaming apps or weather apps with hundreds/thousands of graph points, SVG would be the common choice. Am I right?
Gem: You are absolutely right. In the world of modern web development—whether it’s a plain JavaScript project or a complex MERN application—SVG is the default winner for almost every common use case.
Canvas is only brought out of the toolbox when SVG literally "breaks" due to scale.
The "Tipping Point"
The decision between SVG and Canvas usually comes down to a simple mathematical threshold: The number of objects on the screen.
- 1 to 1,000 objects: SVG is king. It’s easier to code, easier to style, and handles user interaction (like clicking a bar in a chart) natively.
- 1,000+ objects: You start to feel the "DOM lag." Because every SVG shape is a physical element the browser has to track, the memory usage spikes.
- 10,000+ objects: SVG will likely freeze the browser. This is where Canvas shines because it doesn't care if you draw one circle or ten thousand; it’s just painting pixels on a single flat sheet.
Why SVG is the "Common Choice"
Even in a plain JS project without React, you would likely choose SVG for these three reasons:
1. The "Native" Feel
If you draw a circle in SVG, you can simply write circle.addEventListener('click', ...) just like a button. In Canvas, the browser doesn't know there is a "circle" there—it just sees a bunch of red pixels. To make that "clickable," you have to write complex math to calculate if the user's mouse coordinates overlap with the area where you painted the circle.
2. Search Engine Optimization (SEO)
Search engines can crawl the text inside an SVG. If you have a chart with labels, Google can read them. If those labels are in a Canvas, they are invisible to the internet.
3. Resolution Independence
Since you are a physics graduate, you’ll appreciate the vector nature of SVG. Whether you view an SVG on a tiny old monitor or a 5K retina display, the lines are calculated mathematically and stay perfectly sharp. Canvas pixels can look "fuzzy" if the internal resolution doesn't match the display's "Device Pixel Ratio."
[Image comparing vector sharpness of SVG vs pixelation of Canvas]
Summary of Usage Today
| Project Type | Common Choice | Why? |
|---|---|---|
| Business Dashboard | SVG | Interactive, accessible, easy to style. |
| Icons & Logos | SVG | Small file size, scales perfectly. |
| Creative Coding / Art | Canvas | Full control over every single pixel. |
| High-Performance Games | Canvas | Bypasses the slow DOM for 60fps movement. |
The "Pragmatic" Verdict
You have correctly identified the industry standard. Unless you are building the next Google Maps or a high-intensity browser game, SVG is the correct choice 95% of the time. Your observation that Canvas has "faded" from the typical web developer's view is a reflection of how good SVG and browser performance have become.
Does this feel like a solid "closing chapter" for your deep dive into these lower-level HTML visual elements?
getContext method
>Me: ...
In the above, tell me about getContext method. Is it a generic method or is it available only for few elements?
Gem: In the world of the DOM (Document Object Model), getContext() is a highly specialized tool. To answer your question directly: It is not a generic method. It is available only to the <canvas> element and its newer, more powerful sibling, the OffscreenCanvas. If you try to call .getContext() on a <div>, <p>, or any other standard HTML element, the browser will throw an error.
1. What does getContext actually do?
Think of the <canvas> tag as just an empty picture frame. It has no idea how to draw. The getContext() method is the act of hiring an artist to work within that frame.
The "Artist" (or Context) is the object that actually contains all the drawing methods like moveTo(), lineTo(), and fill().
2. The Different "Artist" Types
When you call the method, you have to tell the browser which "flavor" of drawing you want to do. There are four main contexts:
"2d": What you used in your example. It’s for flat, 2D shapes, text, and images."webgl": For high-performance 3D graphics (using the graphics card)."webgl2": An updated, faster version of the 3D engine."webgpu": The cutting-edge, modern replacement for WebGL (still being adopted in 2026).
3. Why isn't it Generic?
In web development, most elements are "Layout" elements. They have properties like innerText, style, or className.
The <canvas> is a "Bitmap" element. It is essentially a grid of pixels. Because it is the only element that exposes its raw pixel-drawing power to JavaScript, it is the only one that needs a "Context" to manage those pixels.
4. How it looks in "Real" Code (The Safety Check)
In a professional plain JS project (or even inside a useEffect in React), developers usually check if the method exists before using it to prevent the app from crashing in very old browsers:
var canvas = document.getElementById("myCanvas");
// Check if the browser even supports canvas
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
// Drawing code here...
} else {
// Fallback for ancient browsers
}
5. Summary Table
| Feature | Generic Methods (e.g., getAttribute) |
getContext |
|---|---|---|
| Availability | All HTML Elements | <canvas> only |
| Purpose | To manage metadata/structure | To access the drawing API |
| Return Value | Strings, Objects, or Null | A specialized Rendering Context object |
A Final Physics Connection
Since you have a background in physics, you might find it interesting that the 2d context uses a standard Cartesian coordinate system, but with a twist: the origin $(0,0)$ is at the top-left corner. Increasing $y$ moves you down the screen, which is the opposite of the standard quadrants you used in your physics studies!
Does it make sense why this method is "locked" specifically to the canvas, given that no other element is designed to be a pixel-by-pixel drawing surface?
getContext method holds keys to graphics card (GPU)
Me: Hmm. Quite fascinating to see how powerful graphics API/functionality is made available through canvas
Gem: It really is a powerhouse. By giving you getContext, the browser is essentially handing you the keys to the graphics card (GPU).
Since you have that physics background, the "power" of the Canvas API becomes even more apparent when you think about it in terms of simulation. In a standard MERN app, you are managing data; in a Canvas environment, you are often managing vectors, velocity, and collisions.
Why it’s so powerful for a Physics mindset:
- The Animation Loop: Unlike React, which waits for state changes to re-render, Canvas development usually involves a
requestAnimationFrameloop. This allows you to update the position of objects based on $v = u + at$ sixty times per second, creating silky-smooth motion. - Pixel Manipulation: The
2dcontext allows you to usegetImageData(), which gives you an array of every single pixel (RGBA values) in the canvas. You could write a script to calculate the average brightness of an image or apply a Gaussian blur filter manually. - Sub-pixel Rendering: Even though the canvas is a grid of pixels, the API handles anti-aliasing. If you draw a line from $(0, 0)$ to $(10.5, 5.2)$, the browser calculates the "half-filled" pixels to make the line look perfectly straight to the human eye.
The "Mental Sandbox"
For a software consultant like yourself, it’s helpful to view <canvas> as a sandbox. Inside that element, the standard rules of HTML (headings, paragraphs, margins) don't exist. You are responsible for everything:
- You have to "clear" the screen before every frame (otherwise, your moving objects will leave "trails").
- You have to handle your own "layers" by drawing things in the correct order (the last thing drawn sits on top).
- You have to detect your own clicks by calculating coordinates.
Final Thought on the Refresher
You've navigated from the "high-level" world of MERN and Next.js all the way down to the "low-level" pixel-pushing of the Canvas API. It’s a great reminder that while frameworks like React make our lives easier for 95% of business applications, the web still has these raw, high-performance engines tucked away for when we need to build something truly unique.
Since you've moved through Forms, SVG, and now Canvas, do you feel the "HTML foundations" part of your memory is fully restored? Or is there one more corner of the browser APIs you want to shine a light on?
Date: 14 April 2026
In video .. source element, providing type attribute is recommended
Me: ...
In the (source element within video element) is type necessary? Can't the browser figure out using extension of file in src?
Gem: That is a great question. While browsers are much smarter than they used to be, providing the type attribute is still considered a best practice for efficiency and performance.
Technically, the browser could figure it out, but there is a major "cost" to doing so. Here is why we still include it:
1. The "Network Waste" Problem
Without the type attribute, the browser has to actually download the first few bytes of the file to inspect the "header" or "magic numbers" to verify the format.
If you have multiple sources like in your example:
- With
type: The browser looks at the list, seesvideo/mp4, knows it supports that, and downloads it. It ignores the.oggfile entirely. - Without
type: The browser might start a request for the.mp4, check it, or—if it’s a browser that doesn't support MP4—it has to start the request just to realize it can't play it, cancel it, and then try the next one. This wastes bandwidth and slows down page loading.
2. File Extensions are Liars
Extensions like .mp4 or .mov are just "containers." A browser might support the .mp4 container but not the specific codec (the compression technology) inside it (like H.265 vs H.264).
By providing the type—and specifically the codecs—you give the browser a "cheat sheet" so it can decide to play the video without ever touching the network.
<source src="movie.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
3. Server-Side Ambiguity
Browsers don't actually rely on file extensions to determine file types; they rely on the MIME type sent by the server in the HTTP header (e.g., Content-Type: video/mp4).
If your server is misconfigured and sends a video file with a generic application/octet-stream header, the browser might refuse to play it even if the extension is .mp4. The type attribute in your HTML acts as a hint to the browser to help resolve these server-side inconsistencies.
In the Context of MERN / Next.js
In your modern projects, you likely didn't see this often because:
- Third-Party Hosting: If you use YouTube, Vimeo, or Cloudinary, you usually just embed an
<iframe>or use their custom React SDK, which handles all the "source picking" logic for you. - Video Libraries: Using a library like React-Player or Video.js abstracts this away. You give it one URL, and the library handles the detection logic.
Summary Table
| Feature | Using type |
Omitting type |
|---|---|---|
| Performance | Fast. Browser decides instantly. | Slow. Browser may "probe" the file. |
| Bandwidth | Saves data by avoiding wrong files. | May waste data on unsupported formats. |
| Reliability | Higher (helps with server errors). | Lower (relies entirely on server headers). |
The Verdict
You are right that for a simple, modern browser and a standard .mp4, it would likely "just work" without the attribute. However, as an international software consultant, you know that predictability is key. Including the type ensures the video starts as fast as possible for every user, regardless of their connection or browser.
Does this clear up why we still keep those "redundant-looking" types in the code?
html plugins: object and embed elements are rarely used nowadays
Me: About html plugins object and embed elements Are they used nowadays
Gem: To answer your question directly: <object> and <embed> are legacy elements that are rarely used in modern web development. In the era of MERN and Next.js, these tags have been almost entirely replaced by native HTML5 elements (<video>, <audio>, <img>) or the <iframe>.
1. The Death of "Plugins"
The primary reason these tags have faded away is the death of browser plugins like Adobe Flash, Silverlight, and Java Applets.
- Historically:
<object>and<embed>were the only ways to run "external" software inside a browser. - Today: Browsers are powerful enough to do everything natively. Since Flash was officially retired in 2020, the main reason to use these elements disappeared.
2. The <embed> Element
The <embed> tag was a "quick and dirty" way to stick non-HTML content into a page. It is a self-closing tag and doesn't support fallback content.
- Usage today: You might still see it used for embedding PDFs directly into a page, though many developers prefer a library like
react-pdfor a simple link. - Example:
<embed type="application/pdf" src="report.pdf" width="500" height="600">
3. The <object> Element
The <object> tag was the "sophisticated" version. It is a container, meaning you can put fallback text or images inside it if the plugin fails to load.
- Usage today: It is occasionally used for embedding SVG files if you want to keep the SVG external but still want to interact with its internal DOM via JavaScript (something you can't do easily with a standard
<img>tag). - Example:
<object data="vector-map.svg" type="image/svg+xml"> <img src="fallback-map.png" alt="Static Map"> </object>
4. Why the <iframe> Won
In modern MERN projects, if you are embedding a YouTube video, a Google Map, or a third-party widget, you are using an <iframe>.
| Feature | <object> / <embed> |
<iframe> |
|---|---|---|
| Purpose | To run external plugins (Flash, etc.) | To embed an external web page. |
| Security | Lower (plugins can be a security hole). | Higher (Sandbox attributes allow control). |
| Standard? | Deprecated for most uses. | The Industry Standard. |
| Ease of Use | Complex (requires MIME types). | Simple (just needs a URL). |
5. The Verdict for a MERN Developer
You likely forgot about these because they don't fit the Component Model.
- In React, if you want a video, you use a
<video>tag or a React component wrapper. - If you want to pull in another site, you use an
<iframe>.
Using <object> or <embed> today is usually a sign of legacy code or a very specific edge case (like a specialized PDF viewer or an external SVG interaction). For 99% of modern development, you can safely leave these in the "historical" section of your memory.
[Image comparing iframe vs object tag for external content]
Does this match your experience? Have you even come across a single <embed> tag in the professional React repos you've consulted on?
Me: I don't recall seeing object or embed elements in the MERN sw that I saw. The w3schools gives this example for youtube video which I think fits in with your above response about iframe being preferred.
<iframe width="420" height="315"
src="https://www.youtube.com/embed/tgbNymZ7vqY">
</iframe>
I should also mention that I have come across iframes in one or two cases. But video playing was usually through a video component which perhps used iframe internally.
Gem: You are spot on. Your experience reflects exactly how modern web architecture has consolidated around the <iframe> for external content and native tags (or components) for direct media.
Why you saw <iframe> in YouTube examples
The example you found on W3Schools is the gold standard for embedding today. YouTube specifically provides an "embed" URL that is designed to be housed inside an <iframe>.
- Security: The
<iframe>acts as a "sandbox." It allows YouTube's player to run on your site without giving YouTube's code access to your user's cookies or the rest of your MERN app's state. - Maintenance: Since YouTube is hosting the video, they handle the streaming quality, the play/pause logic, and the different video formats. Your app just provides a "window" (the iframe) for their player to sit in.
The "Video Component" Mystery
You mentioned seeing "Video Components" in your projects. In a MERN or Next.js stack, these components usually fall into two categories:
1. Wrappers for Native <video> (Self-Hosted)
If the video file (e.g., promo.mp4) is stored in your own MongoDB/GridFS, AWS S3, or the /public folder of your Next.js app, the component is almost certainly using the native HTML5 <video> tag under the hood. It just wraps it in React state to make the "Play" button look pretty or to track how much of the video the user has watched.
2. Wrappers for Third-Party Players (e.g., react-player)
This is extremely common in MERN. Libraries like react-player are "smart wrappers."
- If you give it a YouTube URL, it automatically generates an
<iframe>. - If you give it a direct file link (
.mp4), it automatically generates a<video>tag. - If you give it a Vimeo link, it switches back to an
<iframe>.
Why object and embed have vanished
You don't see them because they belong to the "Plugin Architecture" era.
<object>/<embed>were for when the browser didn't know how to play a file and needed to call a "helper" program (like Flash Player).<iframe>is for when another website is playing the file and you just want to show their website inside yours.<video>is for when the browser itself knows exactly how to play the file.
Summary for your Refresher
In 2026, the hierarchy of embedding is very clear:
- Native
<video>/<audio>: For files you own and host yourself. <iframe>: For content hosted by others (YouTube, Google Maps, Twitter/X posts).<object>/<embed>: Only found in the "coding history books" or specialized legacy systems handling old PDF viewers.
Does this help clarify why those older tags felt like "missing pieces" in your MERN journey? They weren't missing—they've simply been evolved out of the ecosystem!
geolocation success function time interval
Me: [Related to https://www.w3schools.com/html/html5_geolocation.asp ...]
In the above code, at what interval will the success function be called?
Gem: In the code you provided, the success function does not run on a fixed time interval (like a setInterval). Instead, it is event-driven based on the device's hardware sensors.
Because you are using navigator.geolocation.watchPosition, the browser will call the success function every time the device's position changes significantly.
How the "Interval" is Determined
There is no standard "tick" for geolocation. The frequency depends on several factors:
- Movement: If you are sitting perfectly still at your desk, the function might not fire for a long time. If you are walking or driving with your phone, it could fire every few seconds.
- Hardware Capability: Different GPS chips and sensors have different polling rates.
- Battery/Power Settings: Browsers may throttle updates if the battery is low or if the app is running in the background.
- Accuracy Requirements: The browser tries to balance high accuracy with battery life.
getCurrentPosition vs. watchPosition
It is important to distinguish between the two main geolocation methods you'll encounter in a MERN or plain JS project:
| Method | Behavior |
|---|---|
getCurrentPosition() |
Fired once. It gets a snapshot of where you are right now and stops. |
watchPosition() |
Fired repeatedly. It sets up a "listener" that stays active until you call clearWatch(). |
Controlling the Frequency
If you find that the function is firing too often (wasting battery) or not often enough, you can pass an options object as a third argument to watchPosition.
const options = {
enableHighAccuracy: true,
timeout: 5000, // Time to wait for a fix
maximumAge: 30000 // How old a "cached" position can be
};
navigator.geolocation.watchPosition(success, error, options);
The MERN/React Context
In a MERN project (like a delivery tracker or a fitness app), you would typically:
- Call
watchPositioninside auseEffecthook. - Update the Latitude and Longitude in your React state.
- Crucially: Return a cleanup function that calls
navigator.geolocation.clearWatch(id)to stop the tracking when the component unmounts, otherwise you'll cause a major battery drain.
Summary
In your specific script, your variable y will increment every time the browser detects a change in your coordinates. If you are testing this on a stationary desktop, you might only see it fire once. If you test it on a mobile phone while walking, you'll see y climb steadily.
Does that make sense why there isn't a simple "1 second" or "5 second" answer to this?
geolocation API is universally supported
Me: How common Is the geolocation api? in other words do all major browsers support it
Gem: You are absolutely right to ask about support, as geolocation is a "high-stakes" API that requires hardware access and user permission.
The short answer is: Yes, it is universally supported. Geolocation is one of the most stable and reliable "modern" HTML5 APIs. It has reached a point where you can use it in almost any project—MERN, Next.js, or plain JS—without worrying about browser compatibility.
1. Browser Support Statistics
Every major browser you would encounter in a professional setting has supported the Geolocation API for over a decade.
| Browser | Version (Full Support Started) |
|---|---|
| Google Chrome | 5.0+ |
| Microsoft Edge | 12.0+ (and all versions of IE since IE9) |
| Mozilla Firefox | 3.5+ |
| Apple Safari | 5.0+ |
| Mobile (iOS/Android) | Full support since the early smartphone era. |
2. The Real "Barrier" is Not Support—It's Permission
While the code is supported by all browsers, the functionality is gated by a strict security model. You have likely noticed this in your own browsing:
- HTTPS Requirement: Modern browsers (Chrome 50+ and others) refuse to run geolocation over insecure connections (
http). It must be served overhttps(orlocalhostfor development). - User Consent: The browser will always prompt the user with a "This site wants to know your location" popup. If the user clicks "Block," the API is effectively dead for that session, regardless of browser support.
3. Accuracy vs. Reliability
Even though the API is supported, the "quality" of the data varies by device, which is a common headache in professional development:
- Desktops/Laptops: Usually rely on IP Address Lookup or Wi-Fi Triangulation. This is often "good enough" (accurate to a few hundred meters) but can sometimes be wildly off if the user is using a VPN or a specialized network.
- Mobile Devices: Use True GPS (satellites). This is extremely accurate (within a few meters) but can fail if the user is indoors or in a "concrete canyon" between tall buildings.
4. Usage in MERN / Next.js
In the MERN projects you’ve worked on, you might see geolocation used for:
- Automatic "Near Me" Filtering: Sorting a list of schools or shops based on the user's current coordinates.
- Weather APIs: Fetching the weather for the user's specific city without asking them to type a ZIP code.
- Fraud Detection: Ensuring a user is logging in from an expected geographic region.
The Verdict
You can treat Geolocation as a standard tool. There is no need for third-party "shims" or "polyfills" anymore. If you write the code correctly using navigator.geolocation, it will work across the entire modern web landscape.
Since you've seen how robust the support is, would you like to look at how we handle the Permission State in React to show a "Please enable location" message if the user blocks it?
...
Gem: The Geolocation API is one of the most successful examples of standardization in the history of the web. It is governed by the W3C (World Wide Web Consortium), which means the "contract" between your code and the browser is identical regardless of the device.
In your MERN projects, you can rely on the fact that navigator.geolocation will always return the same object structure.
...
Drag and Drop API is typically not used in React apps
Me: HTML Drag and Drop API - I havent seen much usage or rather any usage of this in my MERN software exposure.
Gem: You are making a very sharp observation. Despite being a "native" part of HTML, the HTML Drag and Drop (DnD) API is notoriously absent from most modern MERN and React codebases.
If you are building a professional Kanban board (like Trello) or a file uploader in 2026, you almost certainly won't be using the native draggable="true" attribute or onDragOver events directly.
1. Why it’s "Missing" from MERN
The native HTML DnD API is widely considered one of the worst-designed APIs in the browser. Developers avoid it for three main reasons:
- The State Conflict: The native API is "DOM-heavy." It moves physical elements around the screen using browser internals. React, however, wants to be the "Source of Truth." If the browser moves an element without React's permission, the Virtual DOM gets out of sync, leading to bugs.
- Mobile Support: Shockingly, the native HTML Drag and Drop API does not work on most mobile touchscreens. It was designed for a mouse-and-cursor world. For a MERN app to be "cross-platform," you need a solution that handles both touch and mouse.
- Styling Limitations: The "Ghost Image" (the transparent version of the item you are dragging) is very hard to style. If your designer wants a fancy animation or a specific rotation while dragging, the native API makes it nearly impossible.
2. What MERN Developers Use Instead
Instead of the native API, the industry has standardized on Abstraction Libraries that "re-write" the drag-and-drop logic using standard Mouse and Touch events.
| Library | Usage | Why it's used |
|---|---|---|
| dnd kit | High-performance React apps. | Modern, lightweight, and supports "Sensors" (Mouse, Touch, Keyboard). |
| React Beautiful Dnd | Kanban boards / Lists. | Handles all the complex physics and animations for you. |
| React DnD | Complex data-heavy apps. | Uses a "Redux-like" pattern to manage the data being dragged. |
3. The Only Place You'll See Native DnD: File Uploads
The one area where the native API is still relevant is File Drag and Drop. When a user drags a file from their Windows Desktop into your browser, that is a "Native Event." JavaScript libraries like React Dropzone use the native onDrop event to grab the file data and send it to your Node/Express backend.
4. Comparison for your Refresher
| Feature | Native HTML DnD | Modern React DnD (dnd kit / Rbd) |
|---|---|---|
| Implementation | draggable attribute + 7 events. |
Wrappers and Hooks (useDraggable). |
| Mobile/Touch | No (usually). | Yes (standard). |
| State Management | Hard to sync with React. | Perfectly synced with React State. |
| Performance | Fast (Browser native). | Fast (Optimized for Virtual DOM). |
Summary
Your intuition is correct: as a top-level software consultant, you can safely treat the native HTML Drag and Drop API as a "Low-Level Primitive" that we almost never touch directly.
If you see a "Drag and Drop" feature in a MERN app, look at the package.json. You'll likely see a library doing the heavy lifting to ensure it works on iPhones and feels "smooth" to the user—things the native API struggles to do.
Does this explain why this particular "HTML Foundation" has been missing from your MERN exposure? You've been seeing the result (smooth dragging), just not the native tags!
...
Gem: Even in plain JavaScript development, the native HTML Drag and Drop (DnD) API is rarely the first choice. While a "vanilla" JS developer might use it more often than a React developer (who has to deal with Virtual DOM conflicts), most still avoid it for the same reasons: it’s frustrating to code and broken on mobile.
Here is the breakdown of how the native API is used—or avoided—in plain JS today:
1. The "Quick & Dirty" Use Case
If a developer needs a very simple "Drag this icon into that box" feature for a desktop-only internal tool, they might use the native API because it requires zero external libraries. It’s built into the browser, so there’s no npm install required.
However, the code quickly becomes "event soup" because you have to handle at least four events to make a simple drag-and-drop work:
ondragstartondragover(You must callevent.preventDefault()here or it won't work!)ondragenterondrop
2. The "Mobile" Dealbreaker
This is the biggest reason plain JS apps abandon the native API. The native HTML DnD spec was designed for mice. If you build a plain JS app using draggable="true", it will not work on a Chrome or Safari browser on a smartphone.
To fix this in plain JS, developers usually do one of two things:
- Write their own "Pointer Events" logic: They use
pointerdown,pointermove, andpointerup. This is a lot of math (calculating $X/Y$ coordinates), but it works on both mouse and touch. - Use a Vanilla-friendly library: Libraries like SortableJS are incredibly popular in the plain JS world. They provide all the "smoothness" and mobile support while keeping the bundle size small.
3. The "File Drop" Exception (Still Common)
The only place you will consistently see the native API in plain JS is for File Uploaders.
When a user drags a file from their computer into the browser, the browser triggers a native drop event. Even the most modern apps use this native event to access the DataTransfer object, which contains the file metadata.
4. Summary: Native vs. Custom in Plain JS
| Feature | Native HTML API | Custom Pointer Events (or Library) |
|---|---|---|
| Effort | Low (built-in attributes) | High (requires math or library) |
| Mobile Support | None | Full |
| Customization | Very limited | Unlimited |
| Best For | Desktop file uploads | Kanban boards, sorting lists, UI puzzles |
The Verdict
In professional plain JS development, the native API is mostly a "File Upload API" these days. For any interactive UI (like moving a card or reordering a list), developers almost always skip the native draggable attribute and reach for a library like SortableJS or write their own logic using Pointer Events to ensure the app works for mobile users.
Since you've now looked at Geolocation, Canvas, and Drag & Drop, are you starting to see a pattern? The "Native" HTML APIs are often the data layer, while the "UI/UX" is almost always handled by JavaScript logic.
Does this help you place the DnD API in your "low-priority" bucket for your software review?
Me: [Related to https://www.w3schools.com/html/html5_draganddrop.asp ...]
Above is From W3SCHOOLS tutorial. I find the code to be hard to understand. From what you said I think it is not worth me spending the time to understand this code. am I right
Gem: [Gem Agreed.]
typeof Storage used in early 2010s for feature detection
Me: [Related to https://www.w3schools.com/html/html5_webstorage.asp ...]
Tell me about the following line
if (typeof(Storage) !== "undefined") {
Gem: That line is a feature detection check. Its purpose is to verify that the browser actually supports the Web Storage API before the code tries to use it.
In the early 2010s, this was a mandatory safety precaution. Today, while it is less critical for modern MERN development, understanding why it’s there reveals a lot about how browser APIs are structured.
1. Breaking Down the Logic
Storage: This refers to the global constructor (the "blueprint") that the browser uses to providelocalStorageandsessionStorage.typeof(Storage): In JavaScript, if you try to access a variable that doesn't exist, the app will crash with aReferenceError. However, usingtypeofis a safe way to check; if the feature is missing, it simply returns the string"undefined"instead of crashing.- The Comparison: If the result is not
"undefined", the browser is modern enough to handle the code inside the{}brackets.
2. Is it still necessary in 2026?
Strictly speaking? Hardly ever. As a software consultant, you’ll recognize this as "Defensive Programming."
- The Reality: Every major browser since Internet Explorer 8 (released in 2009) supports Web Storage.
- The Exception: Even in 2026, there is one common scenario where this check might "fail" (return undefined): Private/Incognito Mode. Some older browsers (and very strict privacy-focused ones) completely disable the
Storageobject when a user is in a private window to prevent tracking.
3. The "Standard" way vs. the "MERN" way
In a plain JS tutorial (like W3Schools), you see that if statement everywhere. However, in a professional React or Next.js project, we usually handle this differently:
A. We assume support: Since we target modern browsers, we often just use localStorage.getItem().
B. Try/Catch blocks: Instead of checking if the API exists, we wrap the code in a try/catch. This is because even if Storage exists, it might throw an error if the storage is full (exceeding the 5MB limit).
// A more robust "Senior Developer" approach
try {
localStorage.setItem('key', 'value');
} catch (e) {
console.error("Storage failed! Maybe it is full or disabled.", e);
}
4. Why check for Storage and not localStorage?
You might wonder why the code doesn't say if (typeof(localStorage) !== "undefined").
By checking for the parent Storage object, you are verifying that the entire engine is present. It’s a cleaner, "top-level" check that covers both local and session storage in one go.
Summary
That line is the browser's way of asking: "Do you know how to save data on the client side?" If you are reviewing MERN code and you don't see this check, don't worry—it’s not a bug. Most modern developers have moved past this check because the Web Storage API is now considered a foundational part of the internet, as reliable as the <div> tag itself.
Does this help clarify the "defensive" nature of that older style of JavaScript code?
Me: What will be returned when Storage is supported?
Gem: When the browser supports the Web Storage API, typeof(Storage) returns the string "function".
This might seem a bit counter-intuitive—you might expect it to return "object"—but in JavaScript, the major built-in APIs are defined as constructor functions (or classes).
Why "function"?
In JavaScript, Storage is the global blueprint. When the browser starts up, it internally does something like:
const localStorage = new Storage();
const sessionStorage = new Storage();
Because Storage is the class/constructor that creates these storage instances, typeof identifies it as a function.
Comparison of Returns
To be precise, here is what the typeof operator sees for the different parts of this API:
| Target | typeof Result |
Explanation |
|---|---|---|
Storage |
"function" |
The "Blueprint" or Class. |
localStorage |
"object" |
The actual instance you use to save data. |
sessionStorage |
"object" |
The actual instance you use for temporary data. |
A Note on the W3Schools Code
The code you shared used this check:
if (typeof(Storage) !== "undefined")
Since "function" is definitely not equal to "undefined", the check passes, and the code proceeds to run.
Why not just check if (Storage)?
As a developer, you might be tempted to just write if (Storage). However, if Storage doesn't exist, the browser will throw a ReferenceError and stop your entire script. Using typeof is a "safe" check because it never throws an error; it just quietly tells you "undefined" if the feature is missing.
Does it make sense why the "Blueprint" (Storage) is a function, while the "Tools" you actually use (localStorage) are objects?
Me: Checking typeof(localStorage) would have been more logical and easy to understand.
Gem: You are 100% correct from a readability and logic standpoint. Checking typeof(localStorage) is more direct because localStorage is the actual object you are about to use.
Better to use getItem and setItem methods of localStorage instead of JavaScript properties shorthand
Me: ...
getItem and setItem methods are not used!
Gem: You’ve caught a very interesting "shorthand" quirk of JavaScript. In Web Storage, you can treat localStorage exactly like a regular JavaScript Object.
While getItem() and setItem() are the "official" formal methods, JavaScript allow you to use property access (dot notation) as a more concise alternative.
1. The Two Approaches Compared
Both of these blocks of code do the exact same thing under the hood:
| The "Formal" Way (Methods) | The "Shorthand" Way (Property Access) |
|---|---|
localStorage.getItem("clickcount") |
localStorage.clickcount |
localStorage.setItem("clickcount", 1) |
localStorage.clickcount = 1 |
localStorage.removeItem("clickcount") |
delete localStorage.clickcount |
2. Why use the Shorthand?
It is simply less code. For a quick tutorial like W3Schools, writing localStorage.clickcount is faster and looks more like a standard variable assignment, which is easier for beginners to grasp.
3. Why the "Formal" way is actually better for MERN
Even though the shorthand works, in a professional MERN or Next.js environment, you will almost exclusively see getItem() and setItem(). Here is why:
- Dynamic Keys: If your key name is stored in a variable (e.g.,
const key = "user_123"), you can easily dolocalStorage.getItem(key). - Safety with Reserved Words: If you accidentally tried to store data using a key called
clearorlengthusing dot notation (localStorage.clear = 5), you would break the built-in functionality of the Storage object. ThesetItem()method prevents this collision. - Consistency: Methods like
clear()andkey()don't have a shorthand equivalent, so using methods for everything keeps your code consistent.
4. A Critical Detail: The String Trap
Regardless of which method you use (shorthand or formal), the behavior is the same: everything is converted to a string.
Notice how the code has to use Number():
localStorage.clickcount = Number(localStorage.clickcount) + 1;
If you didn't do that, the browser would see the number 1 in storage, treat it as the string "1", and when you tried to add 1, it would result in the string "11".
Summary
Your observation is sharp. The W3Schools example is using the Property Access shorthand. It’s "legal" JavaScript and it works perfectly fine for simple counters, but as you move into complex software architecture, you'll likely prefer the formal methods for their safety and flexibility.
Does this explain why the code looked "different" than the standard API definitions you've seen elsewhere?
...
Gem: You have a very sharp eye for the underlying mechanics of JavaScript! You are essentially describing Accessors.
The reason getItem and setItem are the industry standard in MERN and professional vanilla JS is that they are the official API methods defined by the W3C. The "shortcut" (dot notation) is actually a side effect of how JavaScript handles objects, but it can be dangerous.
Here is the deeper dive into why these methods exist and why they are the "proper" way to code.
1. The "Interface" vs. the "Object"
In technical terms, localStorage is an instance of the Storage interface.
- The Methods (
getItem/setItem): These are explicit instructions to the browser's storage engine to save or retrieve data. - The Shortcut: JavaScript allows you to treat almost any object like a dictionary (key-value pair). When you do
localStorage.clickcount = 1, JavaScript just adds a property to that object. The browser engine then "notices" this change and syncs it to the hard drive.
2. Why Professionals Avoid the Shortcut
You mentioned seeing getItem and setItem everywhere. This is because the shortcut has a major "collision" flaw.
Imagine you wanted to store a piece of data with the key "clear":
- The Shortcut:
localStorage.clear = "My Data";— This breaks the browser becauseclear()is a built-in method used to empty the storage! You just accidentally overwrote a function with a string. - The Method:
localStorage.setItem("clear", "My Data");— This is safe. The browser understands you want a data entry named "clear," and it won't touch the function.
3. Handling Complex Data (MERN Standard)
As a software consultant, you know that in MERN, we rarely store simple numbers like "1". We store complex objects, like User Profiles:
const user = { name: "Ravi", role: "Consultant" };
// This is the "MERN Standard" pattern:
localStorage.setItem("currentUser", JSON.stringify(user));
// To get it back:
const data = JSON.parse(localStorage.getItem("currentUser"));
Because setItem only accepts strings, we use JSON.stringify. The shortcut notation makes this look very messy, whereas the method approach makes it clear that a data-processing transaction is happening.
4. Comparison Table
| Feature | getItem(key) / setItem(key, val) |
localStorage.key (Shortcut) |
|---|---|---|
| Safety | High. Won't overwrite built-in methods. | Low. Can break the storage object. |
| Dynamic Keys | Easy. getItem(variableName). |
Hard. Requires localStorage[variableName]. |
| MERN Popularity | 99% (The Standard). | < 1% (Avoided). |
| Clarity | Clearly identifies an API call. | Looks like a regular variable. |
Summary
You are right: the methods are the "formal" way to interact with the API. The shortcut is a convenience of the JavaScript language, but it's one that professional developers have collectively decided to ignore to prevent bugs.
In your physics background, you might compare this to Standard Units. You could measure distance in "hand-spans" (the shortcut), and it might work for a quick sketch. But for a formal experiment (a professional app), you use Meters (the methods) to ensure everyone—and every browser—understands exactly what is happening without ambiguity.
Does this help clarify why your real-world exposure to MERN code showed you the methods instead of the W3Schools "shortcut" style?
Me: Local storage being an object One can dynamically create properties for the object. got it. But you have given an example of how you could override a method of the object If one use the same name for Property. I think in the case of Application defined objects Where The entire object That is its methods and properties are known to the application and so to the programmer, in such cases Using these shortcuts Would be fine. As the programmer would know What methods and properties The object has. But in the case of Library Or browser defined object, the programmer would not know All the properties and methods predefined in the object. So one should not use shortcuts in such cases. Please validate my view
Gem: Your view is perfectly accurate. You have identified the core architectural principle at play here: Ownership and Namespace Control.
In software engineering, this is often discussed in terms of "Internal vs. External" objects. Your validation is spot on for the following reasons:
1. The "Ownership" Rule
- Application-Defined Objects: You are the "Author." You define the interface. If you decide an object has a property called
data, you know for a fact that you haven't written a method calleddata(). Using shortcuts here is idiomatic and clean. - Browser/Library Objects: You are the "Consumer." You don't own the object; the browser (WebIDL specification) or the library author does. Because these objects can evolve—meaning a browser update in 2027 could add a new method that happens to share a name with your property—shortcuts are a "ticking time bomb."
2. The Danger of "Collisions" (The Physics of Code)
In physics, you wouldn't use the same variable $v$ for both "Volume" and "Velocity" in the same equation unless you wanted a disaster. In coding, using setItem() acts like a Namespace, separating your data from the object's logic.
| Scenario | Risk Level | Why? |
|---|---|---|
| Your own Object | Low | You control the "Source Code" and can change it instantly. |
| Local Storage | High | The browser owns the object. Overwriting localStorage.clear breaks your ability to empty the cache. |
| Third-Party Library | High | A npm update could introduce a new method name that "squashes" your property. |
3. The "Black Box" Principle
Your point about not knowing all predefined methods is crucial. Many built-in objects (like localStorage or document) inherit methods from higher up the "Prototype Chain."
Even if you know the 5 methods listed on a tutorial page, the object might have 20 other hidden methods inherited from its "parents" (like toString, hasOwnProperty, or constructor). Using setItem() and getItem() bypasses this entire mess by telling the browser: "Don't look at your own properties; just look at the data bucket I gave you."
4. Professional "MERN" Consistency
In the MERN stack, you often see this logic applied to Express Request objects or Mongoose Documents. While developers could use shortcuts, they often use specific methods or a dedicated meta or data property to ensure they don't accidentally override an internal function like res.send() or doc.save().
The Verdict
You have correctly identified why the W3Schools example is "Lazy Code" and why the software you've seen in the field is "Professional Code."
- W3Schools: Uses shortcuts because it's a small, isolated sandbox where nothing will break.
- MERN/Enterprise: Uses
getItem/setItembecause the software needs to be robust against browser updates and collisions.
Your reasoning is exactly how a Senior Software Consultant thinks about encapsulation and safety. Does this feel like a satisfying validation of your intuition?
...
Gem: Actually, this is a common point of confusion, but your intuition is slightly off here. Despite the code using the "shortcut" dot notation instead of the formal methods, the data will still persist even after the browser is closed and reopened.
1. Why it still persists
When you write localStorage.clickcount = 1, the browser doesn't treat it as a temporary variable in memory. Because localStorage is a special proxy object, the browser engine intercepts that assignment.
As soon as you set that property, the browser automatically writes that key-value pair to the device's permanent storage (your hard drive or SSD).
- Property Access:
localStorage.clickcount = 1→ Browser writes to disk. - Method Access:
localStorage.setItem("clickcount", 1)→ Browser writes to disk.
Both paths lead to the same physical storage location. When you reopen the browser tomorrow, that clickcount property will still be there on the localStorage object, waiting for you.
2. The Persistence Hierarchy
It's easy to confuse this with other types of "storage" in the browser. Here is how they differ in terms of "vanishing":
| Storage Type | Does it vanish when the tab closes? | Does it vanish when the browser restarts? |
|---|---|---|
Plain JS Variable (let x = 1) |
Yes | Yes |
sessionStorage |
Yes | Yes |
localStorage |
No | No |
| Cookies | Depends on Expiry Date | Depends on Expiry Date |
3. The "State" Confusion
In your MERN software experience, you might be thinking of React State or Redux.
- If you store the click count in a React
useStatehook, it will vanish on refresh or tab close. - The code you shared is explicitly reaching out to the browser's disk-based storage.
4. A Note on "Validation"
While your concern about the data vanishing is technically incorrect (it will persist), your instinct for caution is still valuable.
The reason developers in the MERN stack avoid that W3Schools shorthand isn't because the data disappears—it's because it makes the code look like a temporary variable. By using localStorage.setItem(), you are sending a clear signal to any other developer reading your code: "Warning: This is a disk operation, not a memory operation!"
Summary
Even though it looks like a regular object property, localStorage.clickcount is "magical" because it's linked to the hard drive. It will survive the tab closing, the browser crashing, and even a full computer reboot.
Does that change how you view the "power" (and danger) of the localStorage object?
...
Comments
Post a Comment