Javascript Tricks, Samples, Tutorials & Howtos
Last updated: 12 Feb 2012

AutoTitle

Sometimes you cannot set meaningful page title when your server generates the page due to framework constraints. Or maybe you'd like to set page title depending upon some user action on the page.

The script allows automatical generation of page title by trying one of the following:

  • Find tag with id autotitle (configurable) within the page;
  • If it isn't found, find first tag with class autotitle (configurable) within the page;
  • If it isn't found, find first H1 tag;
  • If it isn't found, find first H2 tag, etc.
... and if at least one such tag was found in document using its text contents (with configurable prefix and postfix applied) for page title.

The script will use jQuery's document ready event if Query is found, falling back to onload event otherwise.

Using the javascript

To use the script perform the following steps:

  • Put it on your server as a separate file and reference it in HTML HEAD:
<script type="text/javascript" src="specify script file URL"></script>
To specify prefix and/or postfix insert the following after script declaration:
<script type="text/javascript">
AutoTitle.titlePrefix = 'your prefix';
AutoTitle.titlePostfix = 'your postfix';
</script>
To change container id and/or class to look for page title text insert the following after script declaration:
<script type="text/javascript">
AutoTitle.lookForId = 'another_id';
AutoTitle.lookForClass = 'another_class';
</script>
To recalculate the page title (after the page has already been loaded) call the following method:
AutoTitle.setup();

Browser compatibility

The javascript snippet above was tested on the following user agents:

Mozilla Firefox 10 Ok.
Microsoft Internet Explorer 9 Ok.
KHTML Google Chrome 16 Ok.
Safari 5.1 Ok.
No Javascript or
Javascript turned off
Any Page title will not change.