How to unobtrusively update the page title using JS (in Rails)

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

Of course, My Blog also appears in my application layout.

The question is, how do I tell my Javascript about the “My Blog” line without duplicating it in my code?

+3
source share
2 answers

Before Ajax will be sent to the server name document.title ("My Blog") on some variable. Then, when the answer comes, 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;
     }
   })
}
+7
source

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

document.myTitlePrefix = 'My Blog - '

and then update the header as

document.title = document.myTitlePrefix + blogPostTitle
+1
source

Source: https://habr.com/ru/post/1709576/


All Articles