How to make "new" notification equal to Gmail?

Asked

Viewed 462 times

3

Hello. I’m looking for how to make a "new" notification equal to Gmail:

Gmail

That is, when there is a new item in the list the "new" tag appears and only disappear after the person views it.

From the looks of gmail nay make a request ajax, I’m not sure. I believe it is something related to Javascript.

I believe it is some kind of plugin type "viewport" IE, when the user views, it shows the tag. But I do not know exactly.

Does anyone know how to do a similar effect?

  • 1

    Be clearer, what you want to know the logic or how to implement?

2 answers

3


Interesting question. I made an example using jQuery and Javascript.

The first step is a function that traverses items that are potentially new and adds the marker when needed:

//marca itens novos
function highlightItems() {
    console.log('--- highlightItems ---');
    //percorre todos os itens
    $('.item-novo').each(function() {
        console.log($(this).text());
        //verifica se o item é recente
        var adicionado = $(this).data('adicionado');
        if (!adicionado || adicionado > updateTimestamp) {
            //cria marcador
            var marcador = $('<span class="new">novo!</span>');
            //adiciona ao item
            $(this).append(marcador);
            //agenda desaparecimento
            marcador.delay(3000).fadeOut(1500, function() { $(this).remove(); });
            //atualizada momento em que foi exibido para não exibir depois
            $(this).data('adicionado', updateTimestamp);
        }
    });
    updateTimestamp = Date.now();
}

If items are added via Ajax, they should be marked with the CSS class item-novo, as in <div class="item">...</div>.

Still in the example, items coming from the server must come with an attribute data-adicionado, the value of which must be an integer number (timestamp ) representing the item date.

The variable updateTimestamp must contain the date the server last returned data to the user.

In addition, it is possible to add events to detect when user is looking at your page. The event focus window (window) will be fired when the user clicks on any part of the window or frame. It is also possible to check if the user has the mouse over the window for some time, using the event mousemove and a timer.

Putting it all together I made the following event handlers:

//lembra se a janela recebeu o foco
var janelaTemFoco = false;

//timer para atualizar a página
var refreshInterval = setInterval(function() {
    //executa ação apenas se o usuário estiver vendo a janela
    if (janelaTemFoco) {
        highlightItems();
    }
}, 1000);

//eventos de foco da janela
$(window).focus(function() {
    console.log('--- focus ---');
    janelaTemFoco = true;
    highlightItems();
});
$(window).blur(function() {
    console.log('--- blur ---');
    janelaTemFoco = false;
});
//se o usuário parar o mouse, também mostra
var mouseInterval = 0;
$(window).mousemove(function() {
    console.log('--- mousemove ---');
    if (mouseInterval == 0) {
        clearInterval(mouseInterval);
        mouseInterval = setTimeout(highlightItems, 1000);
    }
});
$(window).mouseout(function() {
    console.log('--- mouseout ---');
    clearInterval(mouseInterval);
    mouseInterval = 0;
});

The timer present in the event, rotate every second and, if the focus is on the window, it highlights the new items.

The first event (focus) also highlights the items whenever the user comes back with the focus to the window. Already the event blur prevents items from being highlighted when the user goes to another window.

Finally, the events of mousemove and mouseout identify if the user has the mouse for at least one second over the window and then highlight the items. Otherwise, for example, if the user just swiped the mouse over the window, it does nothing.

I did a functional test, but without the refresh part of the server. Items are generated randomly every 5 seconds.

Demo at Jsfiddle

  • 1

    Dude, fantastic!! I was doing some fiddle stuff too because I think this gmail thing is really interesting... I think your answer is the best. I’m still trying to fully understand

0

All messages have one status, and it controls the way messages are displayed (a simple replace of CSS classes). In the case of ajax requests, yes, they do exist, but are executed periodically. Gmail relies heavily on LocalStorage to ensure performance.

If you have a JSON to store your messages:

{
    id : 123456789456,
    subject : "Teste"
    status : 1 // Nova mensagem
} (...)

It is simple to apply this concept by basing it on periodic communication with the server, using for example the standard loop that does not match requests:

function sync() {
    setTimeout(function() {
        // Faz operações de sincronização

        if (finished) // Se a operação atual terminou
            sync(); // Re-executa a função
    }, 30000); // Sincroniza a cada 30 s
}

Browser other questions tagged

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