Add bookmark system [closed]

1

Recently in a project, the need arose to create a system that can be evaluated by the user, and in this case, only the "favorite" was requested. The user will only click on the "heart" and +1 will be added to each click. But without the use of plugin and tals, only in Jquery, HTML and CSS.

    
asked by anonymous 24.12.2015 / 18:01

1 answer

2

You can use Web Storage API seen that the only requirement is to maintain this information when you reload the page, through window#localStorage() and window#sessionStorage() is possible persist the data. In addition to the two links above, in this question has the explanation of the difference between them.

I set up an example but I could not post it here, SOpt does not let security. So I created a Fiddle to view and test online. Click the Favorites button a few times and refresh the page.

<a href='#' id='count'>Incrementar contagem</a> <!-- botão -->

<p>Total: 
   <span class='badge'></span>                  <!-- total de favoritos -->
</p>       
/*** 
 * Chave usada para armazenar e recuperar as informações salvas
 * no mapa do localStorage.
 */
var FAVORITES_KEY = 'fav';

/** Altera o texto da 'badge' com o total de Favoritos. */
function updateBadge(){
  $('.badge').text(getFavoritesCount());
}

/** Obtém o total de favoritos. */
function getFavoritesCount() {
  var count = localStorage.getItem(FAVORITES_KEY);
  return !count ? '0' : count;
}

/** Adiciona '1' ao total de favoritos. */
function incrementFavorites(){
  var count = parseInt(getFavoritesCount()) + 1;
  localStorage.setItem(FAVORITES_KEY, count);
}

// Quando '#count' for pressionado, é incrementado '1' ao total de
// Favoritos e atualizado a contagem em '.badge'.
$('#count').on('click', function(){
  incrementFavorites();
  updateBadge();
});

// É feita uma primeira chamada para exibir o '0' quando
// ainda não existir nenhum valor em 'FAVORITES_KEY'.
updateBadge();

Remembering that this data is saved locally, if there is a need to retrieve the value to send to the server you can call getFavoritesCount() and get the total of Favorites.

And a final observation, this feature was not implemented in Opera Mini as can be seen in this link .

    
24.12.2015 / 19:12