Markup such as

<div id="Player1"></div> <div id="Player2"></div> ... <div id="Player100"></div> 

Browser cookies are written id blocks for example

 Player1 Player5 Player30 

etc

How to display blocks with id that are not in cookies? Or register display:none; for blocks that are in cookies.

I write to cookies by this script.

 var views = { save: function(b){ var a = localStorage['level']; a = a ? JSON.parse(a) : new Object; var i = a[b] ? a[b] : new Object; i[b] = b; a[b] = i; if(b && !$('#Player' + b).hasClass('views')){ $('#Player' + b).addClass('views'); localStorage['level'] = JSON.stringify(a); console.log('#Player' + b + ' addClass views'); } }, check: function(b){ var a = localStorage['level']; a = a ? JSON.parse(a) : new Object; $(b).find('a').each(function(){ var id = $(this).attr('id').replace('Player', ''); if(a[id]){ $('#Player' + id).addClass('views'); console.log('#Player' + id + ' addClass views'); } }); } } views.check('.play_list'); $(function(){ $('.play').click(function(e){ var id = $(this).attr('id').replace('Player', ''); views.save(id); e.preventDefault(); }); $('.clear').click(function(e){ localStorage['level'] = ''; $('.play_list').find('a').each(function(){ var id = $(this).attr('id').replace('Player', ''); if(id && $('#Player' + id).hasClass('views')){ $('#Player' + id).removeClass('views'); console.log('#Player' + id + ' removeClass views'); } }); e.preventDefault(); }); }); 
  • one
    In your example code, cookies are not used ! - Dmitriy Simushev
  • var i = a[b] ? a[b] : new Object; i[b] = b; a[b] = i; It feels like I'm reading minified code :) - Michael P. Bazos

1 answer 1

Cookies:

 Object.keys(Cookies.get()).forEach(function (idPlayer) { $('#' + idPlayer).hide(); }) 

Watch js fiddle

NB: To simplify the code using a small js-cookies library, you can also read document.cookie if you do not want to add it.

localStorage:

localStorage is a regular object with properties and values. Therefore, let's say you save the identifiers with the help of localStorage.setItem('Player1', '...') , the process will be absolutely similar:

 Object.keys(localStorage).forEach(function (idPlayer) { $('#' + idPlayer).hide(); }) 

js fiddle

  • How to use with localStorage - steep
  • Quite similarly, added in response. - Michael P. Bazos
  • Help to alter my code to normal. It only adds the views class (with memorization) to the link (with #Player ) that was clicked. - steep
  • #Player (there are different numbers) - steep