How to unobtrusively update the page title with JS (in Rails)
-
06-09-2019 - |
Question
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?
Solution
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; } }) }
OTHER TIPS
I would go this way (dirty, but works well):
document.myTitlePrefix = 'My Blog - '
and then update title as
document.title = document.myTitlePrefix + blogPostTitle
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow