To smoothly scroll to a <div> by ID using jQuery, validate that jQuery ($) and a non-empty target ID are provided (typeof / instanceof checks), locate the target element safely (id selector or document.getElementById(id)), animate html, body scrollTop with $("html, body").stop(true).animate({ scrollTop: targetOffsetTop }, duration, easing) inside a try / catch block, and use a Map when tracking scroll presets or target metrics so dynamic keys never collide with Object.prototype properties.
1. Smooth Scrolling to a <div> by ID with Input Validation and try / catch
Stop any running scroll animation first (.stop(true)), compute the element’s vertical offset relative to the document (offset().top minus any fixed-header offset), and animate html, body inside try / catch:
// Smoothly scroll to a target <div> element by ID using jQuery with validation and try / catch
function smoothScrollToDivById(targetId, {
duration = 500,
headerOffsetPx = 0,
easing = "swing",
jqueryRef = (typeof $ !== "undefined" ? $ : null)
} = {}) {
if (typeof jqueryRef !== "function") {
throw new TypeError("Expected jqueryRef to be a valid jQuery ($) function.");
}
if (typeof targetId !== "string" || targetId.trim().length === 0) {
throw new TypeError("Expected targetId to be a non-empty string.");
}
if (typeof duration !== "number" || !Number.isFinite(duration) || duration < 0) {
throw new RangeError("Expected duration to be a non-negative finite number.");
}
if (typeof headerOffsetPx !== "number" || !Number.isFinite(headerOffsetPx)) {
throw new TypeError("Expected headerOffsetPx to be a finite number.");
}
if (typeof easing !== "string" || easing.trim().length === 0) {
throw new TypeError("Expected easing to be a non-empty string.");
}
try {
const cleanId = targetId.trim().replace(/^#/, "");
const domTarget = typeof document !== "undefined" ? document.getElementById(cleanId) : null;
if (!(domTarget instanceof HTMLElement)) {
throw new Error(`No DOM element found with ID "${cleanId}".`);
}
const $target = jqueryRef(domTarget);
const $scrollRoot = jqueryRef("html, body");
const rawTop = $target.offset().top;
if (typeof rawTop !== "number" || !Number.isFinite(rawTop)) {
throw new RangeError(`Unable to determine valid vertical offset for #${cleanId}.`);
}
const finalScrollTop = Math.max(0, Math.round(rawTop - headerOffsetPx));
$scrollRoot.stop(true).animate(
{ scrollTop: finalScrollTop },
{
duration,
easing: easing.trim()
}
);
return new Map([
["targetId", cleanId],
["targetScrollTop", finalScrollTop],
["durationMs", duration],
["headerOffsetPx", headerOffsetPx]
]);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Failed smooth scrolling to ID "${targetId}": ${message}`);
}
}
// Example usage:
// try {
// const scrollMeta = smoothScrollToDivById("section-features", {
// duration: 600,
// headerOffsetPx: 72
// });
// console.log("Scrolling to:", scrollMeta.get("targetId"), "at Y:", scrollMeta.get("targetScrollTop"));
// } catch (error) {
// console.error(`${error.name}: ${error.message}`);
// }
- Use
document.getElementById(cleanId)before wrapping with jQuery: Avoids CSS selector escaping issues when an ID contains special characters (such as:or.). - Call
.stop(true)before.animate(...): Prevents animation queue buildup when users click anchor links repeatedly.
2. Managing Scroll Presets and Section Targets with a Map
When a page has multiple section targets or layout presets (such as fixed navbar heights across breakpoints), store configurations in a Map so dynamic keys never collide with Object.prototype properties:
// Execute a smooth scroll using a named scroll preset stored in a Map
function scrollToSectionWithPreset(sectionKey, presetsMap, {
jqueryRef = (typeof $ !== "undefined" ? $ : null)
} = {}) {
if (!(presetsMap instanceof Map)) {
throw new TypeError("Expected presetsMap to be a Map instance.");
}
if (typeof sectionKey !== "string" || sectionKey.trim().length === 0) {
throw new TypeError("Expected sectionKey to be a non-empty string.");
}
try {
const cleanKey = sectionKey.trim();
const presetConfig = presetsMap.get(cleanKey);
if (typeof presetConfig !== "object" || presetConfig === null || Array.isArray(presetConfig)) {
throw new Error(`No scroll preset found for key "${cleanKey}".`);
}
return smoothScrollToDivById(presetConfig.targetId, {
duration: presetConfig.duration ?? 500,
headerOffsetPx: presetConfig.headerOffsetPx ?? 0,
easing: presetConfig.easing ?? "swing",
jqueryRef
});
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Failed executing scroll preset "${sectionKey}": ${message}`);
}
}
// Example usage:
// try {
// const sectionPresets = new Map([
// ["pricing", { targetId: "pricing-div", duration: 550, headerOffsetPx: 64 }],
// ["faq", { targetId: "faq-div", duration: 450, headerOffsetPx: 64 }]
// ]);
// const resultMap = scrollToSectionWithPreset("pricing", sectionPresets);
// console.log("Scrolled target:", resultMap.get("targetId"));
// } catch (error) {
// console.error(`${error.name}: ${error.message}`);
// }
- Use
Maprather than{}for section/preset registries: AvoidsObject.prototypecollisions (constructor,toString,hasOwnProperty) on dynamic section names. - Adjust
headerOffsetPxfor sticky or fixed top bars: Prevents the top of the target<div>from sitting hidden underneath a fixed navigation bar.
3. html, body Compatibility, Reduced Motion, and Scroll Caveats
Keep these jQuery smooth-scroll details in mind in production pages:
- Animate both
htmlandbody($("html, body")): Ensures cross-browser compatibility across Chromium, Firefox, and Safari without picking only the non-scrolling root element. - Respect
prefers-reduced-motionwhen appropriate: Users who prefer reduced motion may expect instant jumps (duration: 0) or native scroll behavior. - Account for dynamic layout shifts (lazy images or async content): If content above the target
<div>loads late,offset().topcan shift during or after the animation.
