NaughtySquid
NaughtySquid

Reputation: 2097

change page title with jquery, without incrementing to it

I'm trying to update the page title a user is on, to add in their current notification count (like facebook does)

I have this:

var current_page_title = $(document).find("title").text();
document.title = '(' + data.title_total + ') ' + current_page_title;

The problem is, it keeps doing this: "(12) (12) page title" - it adds the bracket number each time.

Is there a way to always use the original title, not the new one that already has the brackets?

Upvotes: 2

Views: 107

Answers (4)

Caique Romero
Caique Romero

Reputation: 633

Look this example, i using regex to get the value in brackets. Try to do it with the title.

https://jsfiddle.net/dsgyjs8m/1/

<input type="text" name="title" id="title" value="(12) lorem ipsum" />
<input type="text" name="newTitle" id="newTitle" value="" />

$(function(){
  var value    = $("#title").val();
  var newValue = value.replace(/([\[(])(.+?)([\])])/g, replacer);

    $("#newTitle").val(newValue);
});

function replacer(match, v1, v2, v3, offset, string) {
  return v1 + (1+parseInt(v2)) + v3;
}

Upvotes: 1

jdubjdub
jdubjdub

Reputation: 613

document.title = '(' + data.title_total + ')' + document.title.replace(/\(*\)/, '');

edited with @serdar.sanri's answer to work for first time

Upvotes: 3

Daniel A. White
Daniel A. White

Reputation: 190945

Just reformulate it every time. Don't blindly append to the current title.

You could cache the current title and append do that.

var title = document.title;

// later
document.title = ... + title;

Upvotes: -3

Ivan Drinchev
Ivan Drinchev

Reputation: 19581

You can save the original value of title outside the code block where you change it and then just append to it.

var pageTitle;

var current_page_title = document.title
                     //  ^ btw, no need for $(document).find("title").text() here
if ( !pageTitle ) { pageTitle = current_page_title; }
document.title = '(' + data.title_total + ') ' + pageTitle;

Upvotes: 4

Related Questions