Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching hashtag to URL with javascript

I want to build an ajax site without sacrificing SEO. My question is: If I have link on my page like this:

   <a href="http://example.com/cats" id="cats">Cats</a>
   <a href="http://example.com/dogs" id="dogs">Dogs</a>

...when each link is clicked I would like to update the address bar with the corresponding hashtag. So, if "Cats" link is clicked the current location will be http://example.com/#cats and I can use this to show my ajax content. If javascript is off or user is search engine, they will go directly to /cats

like image 694
alooficha Avatar asked Mar 02 '10 20:03

alooficha


People also ask

Can you use hashtags in URL?

In a URL, a hash mark, number sign, or pound sign ( # ) points a browser to a specific spot in a page or website. It is used to separate the URI of an object from a fragment identifier. When you use a URL with a # , it doesn't always go to the correct part of the page or website.

Why hashtag is used in Javascript?

'#' is used to selected a certain element you gave an ID to, it's mostly used because if a selection has multiple of the target such as two divs, you can select each on individual one directly. The # is used mostly for convenience , it's a quick and easy way to tell if something is an ID.


2 Answers

You can change the location.hash property, it will change the current anchor identifier without navigating away form the page, for example you could:

<a href="http://mysite.com/cats" id="cats" class="ajaxLink">Cats</a>
<a href="http://mysite.com/dogs" id="dogs" class="ajaxLink">Dogs</a>

Then:

$('.ajaxLink').click(function (e) {
  location.hash = this.id; // get the clicked link id
  e.preventDefault(); // cancel navigation

  // get content with Ajax...
});​
like image 78
Christian C. Salvadó Avatar answered Oct 23 '22 01:10

Christian C. Salvadó


Google will index a hash if it has an exclamation mark in the form: #!dogs

It then assumes that these are AJAX-oriented:

  • Google's FAQ about AJAX
  • Google's guide on how to make AJAX website crawlable
like image 16
anon Avatar answered Oct 23 '22 01:10

anon