Article

Demo

https://cdn.jsdelivr.net/npm/[email protected]/dist/js.cookie.min.js
Copy to clipboard

When a user is on an eCommerce site he might cycle through various pages as he picks items to buy.

Cookies are a way we remember items picked by the user as he moves from one page to another.

In this example use arrays to store picked goods in our cookie. https://raw.githubusercontent.com/finsweet/jqueryCourse/main/cookies/ex20.js?actionable=true

If we the shopping cart cookie exists we just add the new product that was clicked if not then we create a new array and store it in a newly created shopping_cart array. Because cookies can only be store text we use the function JSON.stringify() to convert our array to text.

Conversely we use the function JSON.parse(Cookies.get('shopping_cart')) to convert our stored text to array

<script>
$(document).ready(function(){
  XT1
});
</script>
Copy to clipboard
Send to Live Demo

Live demo

<style>.list li {cursor: pointer;} .list li:hover{opacity:.7;}</style><div id="minidivpage" class="example-live"><h4 class="heading-4">Pick Shopping items</h4><ul role="list" class="list"><li>Beer</li><li>Deodrant</li><li>Soda</li><li>Milk</li></ul></div>

<script>    
$(document).ready(function() {
  XT1
});
</script>
<script>
  
</script>
Copy to clipboard
Press the Run Demo button to execute the scripts above.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Your browser is too small

Resize your browser to be at least 769px wide.