Grabbing part of the url

I want to be able to grab an id (#term) from the end of a url (http://website/page/#term) with Javascript. Not sure how to do that.

I then want to use it in coordination with the following bit of code and run it just after the page has loaded.

$('#filters a').find('.active').removeClass('active');
$('#filters a').find('#term').addClass('active');

Hi reedbird,

You can use window.location.hash to get that part of the URL. Check this page for more information.

Thanks! Appreciate it!

Now, technically wrong forum here, but how could I get that part of the url with php?

Unfortunately you can’t - that part of the url (the fragment) isn’t passed through to the server, it’s only available to the browser. If you need that value, you’d have to get it via JS and pass it to your script.

Edit: If you have a URL as a string (eg. that’s been passed to your script as input) you can extract the various parts (including the fragment) using PHP’s [fphp]parse_url[/fphp] function.


I think using it as javascript is going to work, but its not quite working properly. I’m looking to pull that information and use it with isotope to filter different items on load based on the hash.

Here is what I have, and its not quite working: (the variable breedername is eventually passed to initialize isotope)

var breeder = window.location.hash;
var breedername = '';
	if ( breeder != '' ) {
		$('#filters a').find('.active').removeClass('active');
		$('#filters a').find(breeder).addClass('active');
                var breedern = breeder.slice(1);
		var breederterm = ".term-";
		var breedername = breederterm.concat(breedern);

Which part of the code isn’t working as you expect?

it’s not functioning at all. the variable breedername still ends up empty even if there is a hash. (I know this because it passes to the isotope filter and everything still shows).

I found an error in my html. so It’s mostly working now! Thanks!