Using jQuery Target Selector to Style URL Hash Elements
This article explains how to use jQuery and the :target
selector to detect the URL hash and dynamically apply styles to the
corresponding element. By combining jQuery's selector engine with window
events, you can highlight sections, tabs, or modal windows instantly
when a user loads a page with a hash fragment or clicks an anchor
link.
Understanding the
:target Selector
In CSS, the :target pseudo-class matches an element with
an id attribute matching the current URL's hash fragment
(for example, #section2). jQuery incorporates this selector
directly into its selection engine. When you query
$(':target'), jQuery locates the specific element in the
DOM whose ID matches the fragment identifier currently in
window.location.hash.
Selecting and Styling on Page Load
When a visitor lands on a page containing a hash (such as
example.com/#about), you can immediately target and style
that element using jQuery:
$(document).ready(function() {
$(':target').css({
'background-color': '#fff3cd',
'border': '2px solid #ffeeba'
});
});Using CSS classes is generally preferable for maintainability:
$(document).ready(function() {
$(':target').addClass('active-target');
});Handling Real-Time Hash Changes
Because users can click in-page navigation links without reloading
the page, the active :target changes dynamically. To keep
styles synchronized, listen for the hashchange event on the
window object:
function updateTargetStyle() {
// Remove the style or class from any previously targeted elements
$('.active-target').removeClass('active-target');
// Apply the class to the current target, if one exists
$(':target').addClass('active-target');
}
// Trigger on hash change and initial page load
$(window).on('hashchange load', updateTargetStyle);Direct Hash Selection Alternative
While $(':target') works directly, you can also extract
window.location.hash directly if you need greater control
or compatibility safeguards:
$(window).on('hashchange load', function() {
var hash = window.location.hash;
// Reset styles
$('.highlight').removeClass('highlight');
// Check if hash exists and corresponds to a valid element
if (hash && $(hash).length) {
$(hash).addClass('highlight');
}
});Best Practices
- Sanitize Hash Input: If selecting elements directly
with
$(window.location.hash)instead of$(':target'), ensure the hash contains valid ID characters to avoid syntax errors with unexpected characters. - Combine with CSS Transitions: Pair the class
toggled by jQuery with CSS
transitionproperties to create smooth visual feedback when navigation links are clicked. - Accessibility: When altering visual styles for
targeted elements, consider updating accessibility attributes, such as
aria-current="true", to inform screen readers of the active content.