Everyday JavaScript and jQuery for Web Forms pages: strings, dates, URLs, mouse position, focus styles and fades
Besides the big topics (forms, grids, AJAX), a Web Forms page needs a handful of small client-side utilities: cut a string, read a date, show the visitor's time, look at the URL, follow the mouse, style the field being edited, fade a message in and out. Each one is a few lines, and each one has a trap that old tutorials fell into. This guide collects them, showing the plain JavaScript that every current browser supports and the jQuery equivalent where a page already uses jQuery.
jQuery or plain JavaScript?
For all the utilities below, plain JavaScript is enough: split, Date, URLSearchParams, location.hash, pointer events and CSS transitions are standard. jQuery remains convenient on pages that already load it, mainly for event binding on many elements and for its animation queue. The examples give both where it makes a difference; when they do not, they use plain JavaScript.
Splitting a string into an array
Text first: values from text boxes often arrive as comma-separated lists.
jQuery has no split function of its own: split is a method of every JavaScript string. jQuery helps with what comes after, such as iterating with $.each, but splitting is plain JavaScript and works the same with or without the library.
Basics
"red,green,blue".split(","); // ["red", "green", "blue"]
"red,green,blue".split(",", 2); // ["red", "green"] (limit)
"abc".split(""); // ["a", "b", "c"]
"no separator".split(","); // ["no separator"]
"".split(","); // [""] (one empty string, not an empty array)
Real input is messy
Users type "sql, jquery , css,,". Clean it in one pass:
function toList(text) {
return text.split(",")
.map(function (s) { return s.trim(); })
.filter(function (s) { return s !== ""; });
}
toList("sql, jquery , css,,"); // ["sql", "jquery", "css"]
// several possible separators: comma, semicolon or new line
"a; b\nc,d".split(/[;,\n]+/).map(s => s.trim()); // ["a", "b", "c", "d"]
A regular expression separator accepts alternatives and repeated separators at once. If the regular expression contains capturing parentheses, the captured separators are included in the result, which is rarely wanted; use (?:…) groups.
With values from ASP.NET controls
<asp:TextBox ID="txtTags" runat="server" placeholder="e.g. sql, jquery, css" />
<ul id="tagPreview"></ul>
<script>
$(function () {
$("#<%= txtTags.ClientID %>").on("input", function () {
var $list = $("#tagPreview").empty();
$.each(toList($(this).val()), function (i, tag) {
$("<li>").text(tag).appendTo($list); // .text() keeps user input as text
});
});
});
</script>
$.each(array, function (index, value) { … }) passes the index first, unlike the native forEach(function (value, index) { … }). Building elements with .text() avoids injecting HTML from the user's input.
Splitting on the server too
The posted text box value must be split and validated again in C#:
string[] tags = txtTags.Text
.Split(new[] { ',', ';', '\n' }, StringSplitOptions.RemoveEmptyEntries)
.Select(t => t.Trim())
.Where(t => t.Length > 0 && t.Length <= 30)
.Distinct(StringComparer.OrdinalIgnoreCase)
.Take(10)
.ToArray();
On .NET 5 and later, StringSplitOptions.TrimEntries trims at the same time. Splitting a date into its parts is a special case that deserves parsing instead: Split a date into day, month and year.
Common mistakes
- Expecting an empty array from
"".split(","): it returns[""]. Filter empty entries as shown above. - Splitting CSV lines with
split(","): quoted fields containing commas break it. Use a CSV parser for real files. - Using
split(".")to get a file extension when names contain several dots: take the last element with.pop(), and handle names without any dot. - Forgetting that
splitwith a string separator is case-sensitive; use a regular expression with theiflag for case-insensitive separators.
Splitting a date into day, month and year
Dates look like strings to split, which is exactly the mistake to avoid.
Given "25/12/2026", it is tempting to split on / and take the three parts. It works until the input arrives as 12/25/2026, 2026-12-25 or with a time attached. Parse the string into a date with an explicit format first; then day, month and year are properties.
C#: parse, then read the parts
using System.Globalization;
string input = "25/12/2026";
if (DateTime.TryParseExact(input, "dd/MM/yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out DateTime date))
{
int day = date.Day; // 25
int month = date.Month; // 12
int year = date.Year; // 2026
string monthName = date.ToString("MMMM", new CultureInfo("en-GB")); // "December"
DayOfWeek dow = date.DayOfWeek; // Friday
}
else
{
// not a valid date in that format: "31/02/2026" is rejected too
}
MMis the month andmmthe minutes; mixing them up is a classic bug.- Pass several accepted formats as an array:
new[] { "dd/MM/yyyy", "d/M/yyyy", "yyyy-MM-dd" }. - With
CultureInfo.InvariantCulture, the/in the format matches a literal slash. With another culture, it means "that culture's date separator", which may be a dot or a dash. - On .NET 6 and later,
DateOnly.TryParseExactrepresents a date without a time.
Why plain Split is fragile
string[] parts = input.Split('/');
int day = int.Parse(parts[0]); // works for "25/12/2026"...
// ...but gives day 12, month 25 for "12/25/2026", and throws for "2026-12-25"
Splitting gives you three numbers but no guarantee they form a date: 31/02/2026 splits happily. Parsing validates the date as a whole.
From a TextBox in Web Forms
An asp:TextBox with TextMode="Date" renders an HTML date input, which always posts yyyy-MM-dd regardless of how the browser displays it, so parse with that format:
DateTime.TryParseExact(txtBirth.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime birth);
For three separate drop-down lists (day, month, year), build the date with new DateTime(year, month, day) inside a try/catch for ArgumentOutOfRangeException, or check day <= DateTime.DaysInMonth(year, month) first.
JavaScript
function parseDmy(s) {
var m = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/.exec(s.trim());
if (!m) return null;
var d = +m[1], mo = +m[2], y = +m[3];
var date = new Date(y, mo - 1, d); // months are 0-based in JavaScript
// reject 31/02 and similar, which Date silently rolls over into March
return date.getFullYear() === y && date.getMonth() === mo - 1 && date.getDate() === d ? date : null;
}
var dt = parseDmy("25/12/2026");
if (dt) console.log(dt.getDate(), dt.getMonth() + 1, dt.getFullYear()); // 25 12 2026
Splitting other strings into arrays is covered in Split a string into an array.
Showing the visitor's local time and a live clock
Time zones are the next trap: the server's clock is not the visitor's.
Server-side code such as DateTime.Now gives the server's time, in the server's time zone. To show visitors their own time, the browser must do it: JavaScript's Date reads the computer's clock and time zone, and Intl.DateTimeFormat formats it in the visitor's language.
Show the time once
<p>Your local time: <time id="now"></time></p>
<script>
var el = document.getElementById("now");
var d = new Date();
el.dateTime = d.toISOString();
el.textContent = d.toLocaleString(undefined, { dateStyle: "full", timeStyle: "short" });
</script>
undefined as the locale means "the browser's language", so a visitor in Germany sees a German date. Pass a locale such as "en-GB" to force one.
A live clock
<p class="clock" aria-live="off"><span id="clock">--:--:--</span> <small id="zone"></small></p>
<script>
(function () {
var fmt = new Intl.DateTimeFormat(undefined, { hour: "2-digit", minute: "2-digit", second: "2-digit" });
var clock = document.getElementById("clock");
document.getElementById("zone").textContent = Intl.DateTimeFormat().resolvedOptions().timeZone;
function tick() {
var now = new Date();
clock.textContent = fmt.format(now);
// schedule the next update at the start of the next second, so the clock does not drift
setTimeout(tick, 1000 - now.getMilliseconds());
}
tick();
})();
</script>
Re-scheduling with setTimeout aligned to the second keeps the display in step with the system clock; a plain setInterval(tick, 1000) can slowly fall behind and skip a second. aria-live="off" stops screen readers from announcing every tick.
The jQuery version
$(function () {
var $clock = $("#clock");
function pad(n) { return (n < 10 ? "0" : "") + n; }
function tick() {
var d = new Date();
$clock.text(pad(d.getHours()) + ":" + pad(d.getMinutes()) + ":" + pad(d.getSeconds()));
setTimeout(tick, 1000 - d.getMilliseconds());
}
tick();
});
jQuery only helps with selecting the element here; the time logic is plain JavaScript. The manual padding produces a fixed 24-hour format regardless of language.
Server time vs client time
- The visitor's clock may be wrong. For anything that matters (deadlines, logs, orders), use server time, stored in UTC (
DateTime.UtcNow). - To show a server timestamp in the visitor's zone, send it in ISO 8601 UTC (
dt.ToString("o")on a UTC value) and format it in the browser withnew Date(iso).toLocaleString(). Converting dates that arrive from JSON is covered in Format a JSON date as a local date. - In ASP.NET Web Forms, render the value into the page, e.g.
<time datetime="<%= order.CreatedUtc.ToString("o") %>">, and let a script convert alltimeelements.
Common mistakes
- Using
getYear()(deprecated, returns years since 1900) instead ofgetFullYear(). - Forgetting that
getMonth()is zero-based: January is 0. - Writing the server's
DateTime.Nowinto the page and calling it "your local time": it is the server's.
Converting /Date(…)/ JSON dates
Dates coming back from ASP.NET page methods have a format of their own.
Call an ASP.NET page method or an ASMX web service from jQuery and a DateTime comes back as a strange string: "/Date(1730707200000)/". That is the Microsoft JSON date format used by JavaScriptSerializer and DataContractJsonSerializer. The number is milliseconds since 1 January 1970 UTC, which JavaScript's Date understands directly.
Parsing /Date(…)/
function parseMsJsonDate(value) {
// matches /Date(1730707200000)/ and /Date(1730707200000+0100)/
var m = /^\/Date\((-?\d+)([+-]\d{4})?\)\/$/.exec(value);
return m ? new Date(Number(m[1])) : null;
}
var d = parseMsJsonDate("/Date(1730707200000)/");
console.log(d.toISOString()); // 2024-11-04T08:00:00.000Z
console.log(d.toLocaleString()); // in the visitor's time zone and language
The optional +0100 suffix, produced by DataContractJsonSerializer for local times, describes the original offset; the millisecond value is still UTC, so it can be ignored for display in the visitor's zone.
With jQuery AJAX
$.ajax({
type: "POST",
url: "Orders.aspx/GetLatest",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (res) {
var order = res.d; // page methods wrap results in "d"
var created = parseMsJsonDate(order.CreatedAt);
$("#created").text(created.toLocaleDateString(undefined, { dateStyle: "medium" }));
});
Calling page methods is explained in Call a server-side method with jQuery AJAX.
Watch the DateTimeKind on the server
JavaScriptSerializer converts local DateTime values to UTC before writing the milliseconds, and treats Unspecified values (typical for values read from SQL Server datetime columns) as local time. If the server runs in a different time zone from the one the data was recorded in, displayed times shift by hours. Store and transmit UTC: mark values with DateTime.SpecifyKind(value, DateTimeKind.Utc) when you know they are UTC.
Prefer ISO 8601
Modern serialisers write dates as ISO 8601 strings: "2024-11-04T08:00:00Z". Both Json.NET (its default since version 4.5) and System.Text.Json do so, and JavaScript parses them natively:
var d = new Date("2024-11-04T08:00:00Z");
Be careful with strings that have no offset: new Date("2024-11-04T08:00:00") is interpreted as local time, while a date-only string "2024-11-04" is interpreted as UTC midnight. Always include Z or an offset for timestamps.
On the server, an ASP.NET Web API or a handler serialising with Json.NET can send ISO dates directly; for page methods, you can return a pre-formatted string such as order.CreatedUtc.ToString("o") in a DTO.
Formatting for display
var fmt = new Intl.DateTimeFormat(undefined, { dateStyle: "medium", timeStyle: "short" });
$("time[data-utc]").each(function () {
var d = new Date($(this).data("utc")); // ISO string with Z
if (!isNaN(d)) $(this).text(fmt.format(d));
});
Creating the formatter once and reusing it is faster than calling toLocaleString with options for every element.
Reading and changing the URL hash
The URL itself is a small store for client-side state.
The part of a URL after # is the fragment, often called the hash. It points to a place inside the page, and scripts use it to remember a tab or a filter. It lives only in the browser: it is never sent to the server, so ASP.NET's Request.Url cannot read it.
Reading it
// URL: https://www.example.com/help.aspx?topic=forms#validation
var hash = window.location.hash; // "#validation" ("" if none)
var name = hash.slice(1); // "validation"
var decoded = decodeURIComponent(name); // handles %20 and other escapes
// From any URL string, not just the current page:
var u = new URL("https://www.example.com/a.aspx#step-2");
console.log(u.hash); // "#step-2"
location.hash includes the #. Decode it before comparing, because a fragment such as #caf%C3%A9 arrives encoded.
Changing it
location.hash = "settings"; // adds a history entry, scrolls to #settings
history.replaceState(null, "", "#settings"); // changes it without a new history entry or scrolling
Reacting to changes
function showTab() {
var id = decodeURIComponent(location.hash.slice(1)) || "overview";
document.querySelectorAll("[role=tabpanel]").forEach(function (p) {
p.hidden = p.id !== id;
});
}
window.addEventListener("hashchange", showTab);
showTab(); // also on first load
With jQuery: $(window).on("hashchange", showTab);. The event fires for links like <a href="#details">, for the back and forward buttons and for script changes through location.hash (not for history.replaceState).
The server never sees it
Browsers strip the fragment before sending the request. If the server needs the value, for example to preselect a tab after a postback, copy it into a hidden field before the form is posted:
<asp:HiddenField ID="hfTab" runat="server" />
<script>
document.forms[0].addEventListener("submit", function () {
document.getElementById("<%= hfTab.ClientID %>").value = location.hash.slice(1);
});
</script>
A Response.Redirect to a URL containing #section works: the browser keeps the fragment of the redirect target. For values the server must read from the URL, use the query string instead: Read the query string in the browser.
Common uses and pitfalls
- Deep links to sections. Give headings an
idand link topage.aspx#section; no script needed. - Remembering UI state. Tabs, filters or an open accordion panel can be stored in the hash so the back button and bookmarks restore them.
- Not for secrets. The hash stays in browser history and can be read by any script on the page.
- Fixed headers hide the target. Add
scroll-margin-topto the target elements in CSS so the heading is not hidden under a sticky header.
Getting the mouse position
Pointer coordinates come with every mouse event, in several reference frames.
There is no global "where is the mouse" property in the browser: the position comes with each mouse or pointer event. The event carries several pairs of coordinates, each relative to something different, and picking the right pair is the whole difficulty.
The coordinate pairs
| Properties | Relative to |
|---|---|
clientX, clientY | The viewport (visible area); unaffected by scrolling |
pageX, pageY | The whole document, including the scrolled-away part |
screenX, screenY | The physical screen |
offsetX, offsetY | The padding edge of the event's target element |
Live display
<p id="pos">Move the mouse</p>
<script>
document.addEventListener("mousemove", function (e) {
document.getElementById("pos").textContent =
"client " + e.clientX + "," + e.clientY + " · page " + e.pageX + "," + e.pageY;
});
</script>
jQuery normalises the same properties on its event object: $(document).on("mousemove", function (e) { … e.pageX … }).
Position inside an element
offsetX refers to whatever element is under the pointer, which may be a child. For coordinates relative to a specific container, compute them:
var box = document.getElementById("canvasArea");
box.addEventListener("mousemove", function (e) {
var r = box.getBoundingClientRect();
var x = Math.round(e.clientX - r.left);
var y = Math.round(e.clientY - r.top);
box.title = x + ", " + y;
});
Touch and pen: pointer events
Mouse events are emulated on touch screens, but not for continuous movement. Pointer events cover mouse, touch and pen with one API and the same coordinate properties:
box.addEventListener("pointermove", function (e) {
// e.pointerType is "mouse", "touch" or "pen"
});
Add the CSS touch-action: none on the element if touch movement should not scroll the page while you track it.
A tooltip that follows the cursor
<style>
#follow { position: fixed; pointer-events: none; padding: .2rem .4rem;
background: #222; color: #fff; font-size: .8rem; border-radius: 4px; display: none; }
</style>
<div id="follow"></div>
<script>
var tip = document.getElementById("follow");
document.querySelectorAll("[data-tip]").forEach(function (el) {
el.addEventListener("mouseenter", function () { tip.textContent = el.dataset.tip; tip.style.display = "block"; });
el.addEventListener("mouseleave", function () { tip.style.display = "none"; });
el.addEventListener("mousemove", function (e) {
tip.style.left = (e.clientX + 12) + "px"; // position: fixed uses viewport coordinates
tip.style.top = (e.clientY + 12) + "px";
});
});
</script>
Because the tooltip is position: fixed, it uses clientX/clientY; an absolutely positioned element in the document would use pageX/pageY. Mouse-only hints are invisible to keyboard and touch users, so keep essential information elsewhere; a focusable alternative is the CSS3 tooltip.
Styling the input that has focus
Visual feedback on forms is now mostly a CSS matter.
Colouring the field the user is typing in helps on long forms. Older tutorials do it with jQuery's focus and blur events; today one line of CSS does the same without script. Both are shown here, with the accessibility rule that matters most: never remove the focus indicator without replacing it.
The CSS way (recommended)
input[type=text], input[type=email], input[type=password], textarea, select {
background: #fff;
border: 1px solid #9aa5b1;
transition: background-color .15s ease, border-color .15s ease;
}
input:focus, textarea:focus, select:focus {
background: #fff8db;
border-color: #0e6a70;
outline: 2px solid #0e6a70;
outline-offset: 1px;
}
ASP.NET TextBox, DropDownList and other input controls render ordinary HTML elements, so these rules apply to them directly. No ids, no ClientID, no script.
The jQuery way
If you need logic, such as highlighting only fields with a certain class or toggling something elsewhere on the page, handle the events. Use a CSS class rather than inline colours so the styling stays in the stylesheet:
<style>
.is-active { background: #fff8db; border-color: #0e6a70; }
</style>
<asp:TextBox ID="txtName" runat="server" CssClass="field" />
<asp:TextBox ID="txtEmail" runat="server" CssClass="field" TextMode="Email" />
<asp:TextBox ID="txtNotes" runat="server" CssClass="field" TextMode="MultiLine" />
<script src="https://code.jquery.com/jquery-3.7.1.min.js"
integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="
crossorigin="anonymous"></script>
<script>
$(function () {
$(document)
.on("focusin", ".field", function () { $(this).addClass("is-active"); })
.on("focusout", ".field", function () { $(this).removeClass("is-active"); });
});
</script>
focus and blur do not bubble, so they cannot be delegated from document. jQuery maps delegated focus/blur to focusin/focusout internally, but writing focusin and focusout makes the intent explicit. Delegation also covers fields added later, for example inside an UpdatePanel that refreshes.
Highlight the whole row
Often it is the label and the field together that should stand out. :focus-within matches a container when any element inside it has focus:
<style>
.row { padding: .5rem; border-radius: 6px; }
.row:focus-within { background: #eef6f6; }
</style>
<div class="row">
<label for="city">City</label>
<input id="city" type="text">
</div>
Keyboard users first
- Do not write
outline: noneon focused fields unless you provide an equally visible replacement. WCAG requires a visible focus indicator (success criterion 2.4.7). - A background colour alone may be too subtle; combine it with a border or outline change, and check contrast against the text.
:focus-visiblelets buttons show their ring only for keyboard focus, but text inputs always match it when focused, so for fields:focusand:focus-visiblebehave the same.
For other jQuery helpers on Web Forms controls see Get and set a TextBox value with jQuery.
Fading elements in and out with jQuery
Finally, the animations jQuery made famous, and when CSS should replace them.
jQuery's fade methods animate an element's opacity. fadeIn and fadeOut also show or hide it with display, fadeTo stops at a given opacity, and fadeToggle switches between the two states. They take a duration, an optional easing and a callback.
The four methods
<button type="button" id="in">Fade in</button>
<button type="button" id="out">Fade out</button>
<button type="button" id="half">Fade to 40%</button>
<button type="button" id="toggle">Toggle</button>
<div id="box" style="display:none;padding:1rem;background:#e6f4f1">Delivery is free this week.</div>
<script>
$("#in").on("click", function () { $("#box").fadeIn(400); });
$("#out").on("click", function () { $("#box").fadeOut("slow"); });
$("#half").on("click", function () { $("#box").fadeTo(300, 0.4); });
$("#toggle").on("click", function () { $("#box").stop(true).fadeToggle(250); });
</script>
| Method | What it does |
|---|---|
fadeIn(duration) | Shows a hidden element, opacity 0 to 1 |
fadeOut(duration) | Opacity to 0, then display: none |
fadeTo(duration, opacity) | Animates to the given opacity; the element stays displayed, even at 0 |
fadeToggle(duration) | fadeIn if hidden, fadeOut if visible |
Durations are milliseconds or the strings "fast" (200 ms) and "slow" (600 ms); the default is 400 ms. Easing is "swing" (default) or "linear" unless you add jQuery UI.
Callbacks, promises and chaining
// run code when the fade ends
$("#notice").fadeIn(300, function () {
$(this).delay(3000).fadeOut(600);
});
// wait for several elements
$(".tip").fadeOut(200).promise().done(function () {
$("#next-step").fadeIn(200);
});
Effects on the same element are queued: calling fadeIn then fadeOut runs them one after the other. delay() only affects the queue, not ordinary code.
Avoid animation build-up
If a user hovers in and out quickly, each event queues another animation, and the element keeps blinking after the mouse has left. Clear the queue first with stop(true), as in the toggle example:
$(".card").on("mouseenter", function () {
$(this).find(".actions").stop(true, true).fadeIn(150);
}).on("mouseleave", function () {
$(this).find(".actions").stop(true, true).fadeOut(150);
});
With ASP.NET panels
An asp:Panel renders a <div>. To fade it in on the client it must be rendered (server Visible="true") but hidden with CSS, for example style="display:none" or a class; a panel with Visible="false" is not in the page at all. After an asynchronous postback, re-run your setup code in a pageLoad() function or a PageRequestManager endRequest handler, because the panel's HTML has been replaced.
Accessibility and CSS alternative
jQuery effects respect jQuery.fx.off = true, which you can set when the user prefers reduced motion: jQuery.fx.off = window.matchMedia("(prefers-reduced-motion: reduce)").matches;. For new code, CSS transitions give the same result with less JavaScript and better performance: see Fade in and out with a CSS3 transition.
The CSS-only version of fades and tooltips, without jQuery, is covered in fade in and out with a CSS3 transition and tooltips with CSS3 transitions. Reading and writing ASP.NET text boxes from script is in get and set a TextBox value with JavaScript.
Checklist
- Trim and filter after
split; parse dates with an explicit format instead of splitting them. - Send dates between server and browser as ISO 8601 in UTC, and format them for display with
Intl.DateTimeFormat. - Nothing after
#reaches the server; never rely on it for security. - Prefer CSS (
:focus-visible, transitions) for visual effects, and respectprefers-reduced-motion.
Sources
- Microsoft Learn: String.Split, StringSplitOptions, DateTime.TryParseExact, Custom date and time format strings, DateOnly, Round-trip ("O") format specifier, JavaScriptSerializer, DateTime and DateTimeOffset support in System.Text.Json.
- MDN: String.prototype.split(), Array.prototype.filter(), Date, Intl.DateTimeFormat, <time>, Date() constructor, Date.prototype.toLocaleString(), Location.hash, hashchange event, History.replaceState(), MouseEvent, Pointer events, getBoundingClientRect(), :focus, :focus-within, :focus-visible.
- jQuery API: jQuery.each(), jQuery.ajax(), Event object, focusin event, focusout event, .addClass(), .fadeIn(), .fadeOut(), .fadeTo(), .fadeToggle(), .stop(), jQuery.fx.off.
- W3C: Understanding SC 2.4.7 Focus Visible.
- rfc-editor.org: RFC 3986, section 3.5 Fragment.