Thursday 23 August 2012

jQuery: extract the page title and URL

   


Sometimes we need to obtain the page title and URL that the user is viewing. This might be useful for different reasons: for example just to create breadcrumbs with customised menus, or simply because we need to gather where the user is.
We are going to use jQuery in order to do that.
Please follow me in this short example.

The code
First of all, we need to insert the jQuery reference in the head of our document:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
In the above case we are going to use the Google library.
Now we need to collect the page URL and the title. In order to do so, we can use two jQuery attributes: href and title, referred to the active document:
<script type="text/javascript">
jQuery(document).ready(function () {
    var pageHref = jQuery(location).attr('href');
    var pageTitle = jQuery(this).attr('title');
    jQuery('#info').html(pageHref + ' - ' + pageTitle);
});
</script>
The above script will gather the relevant information when the document is ready and then add it to a page element with id="info". So we just need to create that element (let's say a div) where we need the information to be displayed.
<div id="info"></div>
and that's all.

Further considerations
We can go even further with the above example. In fact the gathered information can be stored for example in a Server Variable or in a cookie and updated every time the page changes. This will actually build a navigation history which we might use later.

If you find it intriguing enough, please share your ideas in the comments section below.
In the meantime, if I survive this hot weather, I will get back to you soon with more posts.

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.