How to update page title with notifications?

Asked

Viewed 713 times

3

I’m making a script that updates the page title and puts how many notifications the user has before the current title. But as it is dynamic and updates this page to check if there are new notifications it is giving problem in the title. I will give an example:

I have 01 notification and the current title of the page is Home, so the title is like "(1) Home", as you check if there are new updates the title is like this: "(1) (1) (1) (1) (1) Home". I wanted some help so this wouldn’t happen!

var title = document.getElementsByTagName("title")[0].innerHTML;
document.title = "('.$total_notifi.') "+title; 

This is the script I have at the moment, where the tag in PHP $total_notifi is the number of user notifications.

  • I think you should run the code change only if the $total_notifi for > that the current $total_notifi. In the process of checking how many notifications it has, return the value only if it is higher. If it is equal, do not run anything.

  • Good morning! There is no way to know how your code works and where is the fault, because you only posted a piece, the update is ajax? Your code here '.$total_notifi. the way it’s mixed with javascript and php doesn’t make sense, it can’t be played, read this: http://answall.com/help/mcve. and only after reading edit the question.

  • Every time you seek the title you are not removing the amount of notifications. previous.

  • @Guilhermenascimento in fact it only brings the value, in case, 1, 2 or 3, logic is a SELECT I do in the bank and brings me this value!

  • @Leonardocarmo I understand, but the problem is not this, the problem is how you put the CODE here in the question, it is not possible to understand if the problem is PHP or JS, if the solution can be php, whether it updates with ajax or not, things like that. You’re saying that it brings from a select, ok is php + mysqli api, but it doesn’t say how the sum is induced. That is, the code has no sense that could be answered, so I provided an answer that tries to make a PARSE of the existing title and by JS itself it updates: http://answall.com/a/108449/3635 - setInterval is only to simulate ;)

3 answers

6


The problem is, you’re probably picking up the title again every time you update it. That’s why the (1) (1) ...

You can save the document title to a variable as soon as you run the script and keep it as if it were a constant once. Later you replace the current title with the value of the variable you picked up as soon as the script was executed, containing the first title.

/*
 * Coloquei um título para exemplificar. No caso, CONST_TITLE pegaria
 * o primeiro valor do próprio título do documento, e.g:
 * 
 *
 *    var CONST_TITLE = document.title;
 *
 */
 
 
var CONST_TITLE = 'Meu título incrível';

function setTitulo(notificacoes) {
  document.title = '(' + notificacoes + ') ' + CONST_TITLE;
}

setTitulo(10);
console.log(document.title); // (10) Meu título incrível

setTitulo(100);
console.log(document.title); // (100) Meu título incrível

console.log(CONST_TITLE);   // Meu título incrível

  • thanks! really worked out! thanks!

5

They may be a problem in PHP if you are not using the sum by Javascript, but if you are in front-end then I will explain what may be occurring.

Supposing the code actually is this (since what was posted makes no sense):

<?php
echo 'document.title = "(' . $total_notifi . ') " + title;';

So the updates now occur on front-end by increment, the way the code here can update the title by accessing the title already coming from php (back-end)

Something like:

document.title += "(1)";

If the problem is really in javascript, then you should convert to int using parseInt for example and also do the necessary treatments, something like:

  • javascript:

    //Valor que virá do ajax ou js que você fez e será somado
    function atualiza(soma) {
        var re = /^\(\d+\)/g;
        var res = document.title.match(re);
    
        //Pega o total no titulo
        var atual = res && res[0] ? parseInt(res[0].replace(/\(|\)/g, "")) : 0;
    
        //Remove o total e os `()` do titulo
        var titulo = document.title.replace(re, "");
    
        document.title = "(" + (atual + parseInt(soma)) + ") " + titulo;
    }
    
    setInterval(atualiza, 1000, 1); //Adiciona +1 (terceiro parâmetro)
    
  • html:

    <title>(<?php echo $total; ?>) Home</title>
    

    However as I have already mentioned, the problem may be in php.

Note that the (<?php echo $total; ?>) is optional and if the update comes from ajax, as it is on Facebook or Twitter, ie the script here can fit any title without having to set in a variable, examples of pages that the (1) will be added:

home:

<title>Home</title>

Blog:

<title>Blog</title>

And Ajax (Jquery example) would be something like:

$.ajax("update.php").done(function(data) {
     atualiza(data);
});

After running it on any page the result will be something like:

home:

(2) Home

Blog:

(2) Blog

That is how I made the title is updated independent of the original content.

  • In fact I am preupado with SEO, each page has its title, so I resgato the current title of the page, previously defined, check if there is notification, if there is I update this title putting the value before it, however as stated in the first reply I can save this preset title in a variable and then update the title by taking this variable and adding the value of the notifications

  • If you’re worried about SEO, then my answer is a better way to go in my view, since the initial title might be something like (1), only one HTML title and it does the Parsing of the title and then plays the (1) on the front... But still the code as described and the proposed solutions lead to a certain confusion of understandings.

  • @Leonardocarmo If you are worried about SEO, then my answer is a better way in my view, since the initial title can be something like (1), only a title in HTML and it makes the title Parsing and then plays the (1) in front, because in the code the (1) is unnecessary (optional) :D ... However still the code as described and the proposed solutions lead to a certain confusion of understandings.

  • @Leonardocarmo updated the answer, gives a read ;)

  • 1

    My level in JS is not very good rs, but I understood your idea, I will structure here and test

3

Hello, you may be withdrawing your previous notification before placing the new one as follows.

var title = document.getElementsByTagName("title")[0].innerHTML;
title = title.substring(title.indexOf(")"), title.length);
document.title = "('.$total_notifi.') "+title; 
alert(title);
  • 1

    If you have more than one digit in the number of notifications the substring, will cut the number or left the parentheses. =/

  • 1

    True, only use str.indexof(")")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.