Explain, please.

How to add an element to the page through .append() , but so that when the page is updated the added element does not disappear?

 $('#button').on('click', function(){ $('body').append('<p>test</p>') }); 
  • 2
    Well, at least localStorage or the database - Air

2 answers 2

Since you have jQuery, the code will be smaller. I agree with the comment about localStorage or DB, but I did not see the answer, so I’ll show the idea with localStorage , in my opinion this approach is simpler. Complement the click method:

 $('#button').on('click', function(){ const element = '<p>test</p>'; // ΠΏΠΎΠ»ΠΎΠΆΠΈΠ»ΠΈ Π² ΠΏΠ΅Ρ€Π΅ΠΌΠ΅Π½Π½ΡƒΡŽ наш элСмСнт $('body').append(element); // Π΄Π°Π±Π°Π²ΠΈΠ»ΠΈ ΠΊ body наш элСмСнт const items = localStorage.getItem('appended'); // ΠΏΠΎΠ»ΡƒΡ‡ΠΈΠ»ΠΈ ΠΏΠΎ ΠΊΠ»ΡŽΡ‡Ρƒ свой элСмСнт var elements = JSON.parse(items) || []; // распарсили ΠΏΠΎΠ»ΡƒΡ‡Π΅Π½Π½Ρ‹ΠΉ элСмСнт elements.push(element); // Π΄ΠΎΠ±Π°Π²ΠΈΠ»ΠΈ Π² массив localStorage.setItem('appended', JSON.stringify(elements)); // записали Π½ΠΎΠ²ΠΎΠ΅ Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ }); 

And also add a block of code that will add elements after the page has refreshed:

 $(document).ready(function() { const items = localStorage.getItem('appended'); // ΠΏΠΎΠ»ΡƒΡ‡ΠΈΠ»ΠΈ ΠΏΠΎ ΠΊΠ»ΡŽΡ‡Ρƒ свой элСмСнт var elements = JSON.parse(items) || []; // распарсили ΠΏΠΎΠ»ΡƒΡ‡Π΅Π½Π½Ρ‹ΠΉ элСмСнт // ΠΏΡ€ΠΎΠΉΠ΄Π΅ΠΌ ΠΏΠΎ элСмСнтам ΠΈ Π΄ΠΎΠ±Π°Π²ΠΈΠΌ ΠΈΡ… ΠΊ body for (var index = 0; index < elements.length; index++) { $('body').append(elements[index]); // Π΄Π°Π±Π°Π²ΠΈΠ»ΠΈ ΠΊ body наш элСмСнт } }); 

Useful links:

    Use cookies

    Static solution: Initially hide this block for the time being, and then show it on click? In the client's cookies, it is necessary to register that this block is already visible and show it immediately upon repeated display.

    Dynamic solution: In the form in which this is done, you can use cookies to save which blocks are shown, and which are hidden, and when you refresh the page, after reading the cookie, you can dynamically add / delete the corresponding blocks.