WP-Mix

A fresh mix of code snippets and tutorials

JavaScript & jQuery: Add Style to Fragment Identifier

It’s easy to style a <div> by targeting its ID. But what if you only want to add style when a specific fragment identifier is targeted via the URL? So for example, your page at /about/ has a table with all the data. When visitors arrive directly at /about/, no extra styles are added. But when a visitor arrives at /about/#contact, extra CSS is added to highlight your contact information. Here is how to do it with JavaScript and jQuery.

JavaScript

Do it with vanilla JavaScript:

if (window.location.hash === '#fragment-id') {
	var element = document.querySelector('#fragment-id');
	element.style.backgroundColor = '#ffff99';
}

Change fragment-id with the name of your fragment ID. Then you can modify the conditional code to apply desired styles or do other things, etc.

jQuery

Here’s how to do it with jQuery:

jQuery('document').ready(function($) {
	if (window.location.hash === '#fragment-id') {
		$('table').closest('td').addClass('highlight');
	}
});

This example changes it up a bit. Instead of applying style to the same #fragment-id found in the URL, it applies the style to the closest matching table cell <td>. To use, change fragment-id with the name of your fragment ID. Then you can modify the conditional code however is necessary.

I hope this gives you some ideas!

★ Pro Tip:

Digging Into WordPressGA Pro