First of all thanks for any future help!
I am creating a notification script that modifies the title tab to make the (1) appear. I am pulling the number of alerts from a notify_count variable updated by the website.
The situation I am facing is that:
1.The (1) appears in tab but is duplicated everytime the newUpdate interval executes.
ex: (1) my site, then (1) (1) my site, etc...
- If notify_count value increases, the changeTitle function doesn't update numb and the same number appears in the tab.
ex: notify_count = 1 -> (1) my site -> notify_count = 2 -> (1) my site
var numb = notify_count.toString();
function changeTitle() {
var newTitle = '(' numb ') ' document.title;
document.title = newTitle; }
function newUpdate() {
var update = setInterval(changeTitle, 2000);
}
CodePudding user response:
You need to check if the title already begins with (notify_count)
. If it does, you have to replace that instead of adding the count again at the beginning.
function changeTitle() {
let prefix = `(${notify_count})`;
if (document.title.match(/^\(\d )\)/) {
document.title = document.title.replace(/^\(\d )\)/, prefix);
} else {
document.title = `${prefix} ${document.title}`;
}
}
}
function newUpdate() {
var update = setInterval(changeTitle, 2000);
}
Another option is to save the original title in another variable when the page loads.
let original_title = document.title;
function changeTitle() {
document.title = `(${notify_count}) ${original_title}`;
}
function newUpdate() {
var update = setInterval(changeTitle, 2000);
}
CodePudding user response:
You are getting a duplicate title e.g.(1) (1) my site
because of this;
var newTitle = '(' numb ') ' document.title;
document.title = newTitle;
You are setting document.title
to newTitle
's value but you are using the existing document.title
value in defining newTitle
. In essence this line is appending "(num)" to the document.title
again and again and again.
The first time through document.title
is "My Site" before you append the "(num)". Then the next time through document.title
is "(1) My Site", which is then used to define newTitle
to be "(1) (1) My Site". etc...
To correct this you can use a RegEx in changeTitle()
to replace only the "(num)" portion of the document.title with String.Replace() or you can define a new var at the top to hold the original document.title
and use that var as the base from which to build your newTitle