views:

448

answers:

2

Whenever I load a blog post onto the page with Ajax, I set the page <title> to "My Blog - BLOGPOST_TITLE".

Of course "My Blog - " appears in my application layout as well.

The question is, how do I tell my Javascript about the string "My Blog - " without duplicating it in my code?

+6  A: 

Before Ajax is sent to server store document.title value ("My Blog") to some variable. Then when response arrives set document.title to document.title + ' - ' + BLOGPOST_TITLE

so you have in HTML:

... < title>My Blog< /title> ...

and in JS:

var TITLE = document.title;

function getBlogSpotEntry() {
   Ajax.Request(url, {
     onSuccess: function(response) {
       var entryTitle = getTitle(response.responseText);

       document.title = TITLE + " - " + entryTitle;
     }
   })
}
Svitlana Maksymchuk
This won't work -- the title of my blog is never "My Blog". I'm always showing a post, so it's always "My Blog - BLOGPOST_TITLE". I could split on the " - " or something, but that's a hack (what if " - " changes).
Horace Loeb
Are you dealing with one particular blog or many different? In the first case it is possible to send one extra ajax request to blog endpoint (not to particular blog entry but to the blog root) - then returned title will be only 'My Blog'.
Svitlana Maksymchuk
Yeah, I could do another AJAX call, though this seems wasteful since I'll actually know the prefix at the time of the initial page load.
Horace Loeb
A: 

I would go this way (dirty, but works well):

document.myTitlePrefix = 'My Blog - '

and then update title as

document.title = document.myTitlePrefix + blogPostTitle
Ilya Birman