Record the selected list item chosen by the user to optimize caching

There's a list of items with a "change view" option for grid, list, and compact views. By default, the grid view is displayed when the user opens the link (which has already been achieved). Now, my goal is to remember the user's choice of view so that when they click on list view and return to the page later, it will display the last chosen view. Check out the JSFiddle here

My code:

$('li').on('click', function(e) {
  if ($(this).hasClass('grid')) {
    $('#container ul').removeClass('list').addClass('grid');
  }
  if ($(this).hasClass('grid')) {
    $('#container ul').removeClass('compact').addClass('grid');
  }

  if ($(this).hasClass('list')) {
    $('#container ul').removeClass('grid').addClass('list');
  }
  if ($(this).hasClass('list')) {
    $('#container ul').removeClass('compact').addClass('list');
  }
  if ($(this).hasClass('compact')) {
    $('#container ul').removeClass('list').addClass('compact');
  } else if ($(this).hasClass('compact')) {
    $('#container ul').removeClass('grid').addClass('compact');
  }
});

$('document').ready(function() {
  $('.menu li').click(function() {
    $(this).siblings().removeClass('active');
    $(this).addClass('active');
    var $div = $('#' + $(this).data('href'));
    $('.demo').not($div).hide();
    $div.slideToggle();
  });
});
.menu ul li button:hover {
  background-color: rgba(206, 0, 0, 1);
}

.active {
  background-color: rgba(30, 30, 30, 1);
}

#container ul {
  list-style: none;
}

#container .buttons {
  margin-bottom: 20px;
}

#container .list li {
  width: 100%;
  border-bottom: 1px dotted #CCC;
  margin-bottom: 10px;
  padding-bottom: 10px;
}

#container .grid li {
  float: left;
  width: 20%;
  height: 50px;
  border-right: 1px dotted #CCC;
  border-bottom: 1px dotted #CCC;
  padding: 20px;
}

#container .compact li {
  float: left;
  width: 30%;
  height: 50px;
  border-right: 1px dotted #CCC;
  border-bottom: 1px dotted #CCC;
  padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu">
  <ul>
    <li class="grid"> <a href='#' id="show2">Grid</a></li>
    <li class="list"> <a href='#' id="show3">List</a></li>
    <li class="compact"> <a href='#' id="show1">Compact</a></li>
  </ul>
</div>

<div id="container">
  <ul class="grid">
    <li>Item 2</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
    <li>Item 7</li>
  </ul>
  <div>
  </div>

Answer №1

To achieve this functionality, consider storing the user's choice as a cookie and then setting the layout based on that stored information when the document loads. Here's an example:

$('li').on('click', function(e) {
  if ($(this).hasClass('grid')) {
    document.cookie = "menuChoice=grid";
    $('#container ul').removeClass('list').addClass('grid');
    $('#container ul').removeClass('compact').addClass('grid');
  }

  if ($(this).hasClass('list')) {
    document.cookie = "menuChoice=list";
    $('#container ul').removeClass('grid').addClass('list');
    $('#container ul').removeClass('compact').addClass('list');
  }
  if ($(this).hasClass('compact')) {
    document.cookie = "menuChoice=compact";
    $('#container ul').removeClass('list').addClass('compact');
    $('#container ul').removeClass('grid').addClass('compact');
  }
});

$('document').ready(function() {
  switch (getCookie("menuChoice")) {
    case 'grid':
      $('#container ul').removeClass('list').addClass('grid');
      $('#container ul').removeClass('compact').addClass('grid');
      break;
    case 'list':
      $('#container ul').removeClass('list').addClass('list');
      $('#container ul').removeClass('compact').addClass('list');
      break;
    case 'compact':
      $('#container ul').removeClass('list').addClass('compact');
      $('#container ul').removeClass('compact').addClass('compact');
      break;
    default:
      break;
  }
  $('.menu li').click(function() {
    $(this).siblings().removeClass('active');
    $(this).addClass('active');
    var $div = $('#' + $(this).data('href'));
    $('.demo').not($div).hide();
    $div.slideToggle();
  });
});

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}
.menu ul li button:hover {
  background-color: rgba(206, 0, 0, 1);
}

.active {
  background-color: rgba(30, 30, 30, 1);
}

#container ul {
  list-style: none;
}

#container .buttons {
  margin-bottom: 20px;
}

#container .list li {
  width: 100%;
  border-bottom: 1px dotted #CCC;
  margin-bottom: 10px;
  padding-bottom: 10px;
}

#container .grid li {
  float: left;
  width: 20%;
  height: 50px;
  border-right: 1px dotted #CCC;
  border-bottom: 1px dotted #CCC;
  padding: 20px;
}

#container .compact li {
  float: left;
  width: 30%;
  height: 50px;
  border-right: 1px dotted #CCC;
  border-bottom: 1px dotted #CCC;
  padding: 20px;
}

</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu">
  <ul>
    <li class="grid"> <a href='#' id="show2">Grid</a>

    </li>
    <li class="list"> <a href='#' id="show3">List</a>

    </li>
    <li class="compact"> <a href='#' id="show1">Compact</a>

    </li>
  </ul>
</div>


<div id="container">
  <ul class="grid">

    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
    <li>Item 7</li>
  </ul>


  <div>

  </div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an error message stating "Buffer is not defined" while working with gray-matter

Encountering an issue when trying to utilize gray-matter in Angular 9, the error message displayed is: ReferenceError: Buffer is not defined at Object.push../node_modules/gray-matter/lib/utils.js.exports.toBuffer (utils.js:32) at push../node_modul ...

Encountered an issue with launching Chrome in Puppeteer for Node.js

My code was uploaded to EC2 AWS, but unfortunately it is not working properly after the upload. Interestingly, it runs correctly on localhost. Despite trying various solutions, I am still facing this issue. Any suggestions on the correct approach to resolv ...

The function defined in the script is not being executed

I encountered an issue in my code. In my script.js file, I have the following function: $(function () { function addColors(basicColors) { ... } }); And in my HTML file: <head> <script src="scripts/script.js"></script> </ ...

Determine the data type of a function's parameter

Given that TypeScript is a superset of Javascript and 'Type' is not present in the resulting js files, does this mean manipulating 'type' will not function as intended? Furthermore, are there any alternative approaches to achieve this ...

Exploring the world of Ajax and managing cookies

I am facing an issue with setting cookies in my login form using ajax when the "remember me" checkbox is checked. Despite having code to handle this scenario, the cookies are not getting set properly. After executing var_dump($_COOKIE), I see that only the ...

Simply double-clicking in the 2D sheets view on the left panel will display PDF files in the Autodesk viewer

After discussing the information in this forum post, I have successfully displayed the 2D sheets view (left panel) in the Autodesk viewer for PDF files and other 2D files. https://i.sstatic.net/OFATj.png https://i.sstatic.net/WXMlT.png However, I am fac ...

Put down a sentence into a JavaScript file

Currently, I am utilizing an array to showcase a series of images on a website: let paintingImages; paintingImages = [ { url: 'images/objects/ron.jpg', alt: 'ron' } ]; This particular Ja ...

Angular.js is failing to display content

<html ng-app = "sampleMod"> <head> </head> <body ng-controller = "sampleCon"> <script src = "bower_components/angular/angular.min.js"></script> <h1>Filters example</h1> C ...

Creating a Circular Design with Text at the Center Using CSS

I'm facing a challenge with this https://i.sstatic.net/zQiF8.png The alignment of the icon is off. I would like to adjust it slightly upwards for better presentation. Below is my HTML (angular): // Icon component <div> <i><ng-c ...

Improving Material UI Responsiveness: A Comprehensive Guide

Could someone please help me resolve the overflow issue in my UI? You can view the overflow here. The second image explains the reason behind it, which you can see here. I am currently working on fixing my UI using React and Material UI. When checking the ...

Connecting Angular components with directives using templates

I created a single file containing directive templates. I use the ng-include directive to append this file to the document. Sometimes, the browser loads the templates before binding them to the directive template, but not always. Visit this link for more ...

AngularJS $http.get request not working as expected

Hi there, I'm currently facing an issue with retrieving data from a webpage for use on my own website. I'm working with AngularJS and attempting to fetch data from . When checking my page in Chrome, I encountered the following error: Refere ...

Can MooTools be used for asynchronous file uploads?

Currently, I am working on file uploading using asp.net: <asp:FileUpload ID="Upload" runat="server" /> <!-- HTML --> Upload.PostedFile.SaveAs(physicalPath + "newAvatarTemp.png"); // codebehind However, I find it frustrating when pages need to ...

Steps for automatically logging in/registering a user upon form submission

My website is powered by Node.JS + Express + Socket.IO and I'm using MongoDB as the database. On one particular page, there is a button that opens a Bootstrap Modal with a register form when clicked. The user can choose to use a login form within thi ...

Issue with Opacity in IE8

The layer opacity works well in Firefox and Chrome, but struggles in IE8. $('document').ready(function () { $('.out-of-stock').each(function () { $('.productImage', $(this)).css('opacity', '.25'); ...

Guide to implementing Vuetify tabs alongside Vue Router

I have a scenario with two Vuetify tabs in this jsfiddle, but the documentation lacks examples of using vue-router with them. After stumbling upon a helpful Medium.com post about integrating Vuetify with vue-router, I came across the following code: <d ...

Is it possible to use Google API to fetch specific sections of a document by referencing headings?

I have a document that I extract text from to insert into my webpage. This document is getting larger as it covers more areas, so I want to streamline the process for my single-page application. Currently, I retrieve the entire document using the code snip ...

Node.js Error: Issue with establishing a connection between Mongoose and MongoDB using connection string

After configuring my connections: const mongoose = require('mongoose') const Post = require('./database/models/Post') mongoose.connect("mongodb://localhost/testdb", { useNewUrlParser: "true", useUnifiedTopology: true }) And setting ...

Problem encountered when attempting to post to a node/express endpoint

It has been a while since I last used JQuery/Ajax instead of axios to connect to an endpoint, am i making any mistakes here? var express = require('express'); var app = express() var bodyParser = require('body-parser'); var path = re ...

Ways to fix a "define is not defined" issue when utilizing jasmine karma with compiled typescript for component testing

I'm faced with an issue in my typescript app where the compiled code is stored in a single file named myjs.js within the js folder. Additionally, I have karma jasmine configured on my workspace. Inside myjs.js, there's a segment of code like thi ...