Utilizing local storage, store and access user's preferred layout options through a click function

Exploring the realm of localstorage for the first time, I am considering its use to store a specific ID or CLASS from my css file. This stored information would then be utilized to render a selected layout (grid/list) in the user's browser upon their interaction (click event). Should I opt for localstorage in this scenario? Or would sessionstorage be more suitable? Alternatively, is there a completely different method that might better serve this purpose? If so, what would it entail?

The goal I aim to achieve: When a user clicks on one of two icons representing "cozy" or "list" views, the chosen CSS layout ID or CLASS must be retained. As the user navigates through other pages on the website, this preference should persist so that upon returning to the initial page, the layout remains unchanged based on their selection. The same principle applies even if the user closes and reopens their browser while on that page.

In addition, implementing a time-based cache feature would be beneficial. For instance, maintaining the user's preferred layout in localstorage for a specified number of days before clearing it.

I would greatly appreciate any assistance as I am at a loss on where to begin with this task. Despite reviewing numerous examples, grasping the concept eludes me, especially since the available illustrations do not align with my requirements.

This is my current progress:

Javascript

// Switching 'Cozy' layout to 'List'
$('.news_nav-options_list').on('click', function () {
    var cozy=document.getElementById('hideClass');
    cozy.style.display="none";

    var list=document.getElementById('showClass');
    list.style.display="block";

    $(this).addClass('active');
    $('.news_nav-options_cozy').removeClass('active');
});

// Switching 'List' layout to 'Cozy'
$('.news_nav-options_cozy').on('click', function () {
    var list=document.getElementById('hideClass');
    list.style.display="block";

    var cozy=document.getElementById('showClass');
    cozy.style.display="none";

    $(this).addClass('active');
    $('.news_nav-options_list').removeClass('active');
});

Below is a demonstration of my progress:

DEMO

I have come across suggestions to utilize ".setItem() and .getItem" methods with localstorage, but I am clueless about how to proceed further. Can localstorage be integrated into the current javascript framework I have implemented?

Answer №1

It seems like there might be a small mistake in this code, but it should help guide you in the right direction towards your desired outcome.

$(document).ready(function(){
    // When the user clicks on 'Cozy' layout option switch to 'List' view
    $('.news_nav-options_list').on('click', function () {
        changeToListView();
    });

    // When the user clicks on 'List' layout option switch to 'Cozy' view
    $('.news_nav-options_cozy').on('click', function () {
        changeToCozyView();
    });

    if (typeof(Storage) !== "undefined") {
        var view = localStorage.getItem("view");
        if (view && view == "cozy") {
            changeToCozyView();
        } else if (view && view == "list") {
            changeToListView();
        } else {
            // The view is not specified or does not match recognized options
        }
    } else {
        // Local storage is not supported by the user's browser
    }        
});

function changeToListView() {
    var cozy=document.getElementById('hideClass');
    cozy.style.display="none";

    var list=document.getElementById('showClass');
    list.style.display="block";

    storagePut("list");

    $(this).addClass('active');
    $('.news_nav-options_cozy').removeClass('active');
}

function changeToCozyView() {
    var list=document.getElementById('hideClass');
    list.style.display="block";

    var cozy=document.getElementById('showClass');
    cozy.style.display="none";

    storagePut("cozy");

    $(this).addClass('active');
    $('.news_nav-options_list').removeClass('active');
}

function storagePut(view) {
    if (typeof(Storage) !== "undefined") {
        localStorage.setItem("view", view);
    } else {
        // Local storage is not supported by the user's browser
    }        
}

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

Steps to modify the CSS of a custom component in Angular 8

I have been attempting to override the css of a custom component selector, however, my attempts have been unsuccessful. I have tried using ":ng-deep" but it hasn't worked. How can I go about finding a solution for this issue? app.component.html: < ...

Trouble Ensues When Using Two Jquery Datatables with the Same Class

I am facing an issue with two jQuery datatables that have the same class names. The search functionality works in one table but not in the other. I need some help reviewing my code to figure out how to fix this. jQuery $('.dataTable th.searchClass&a ...

Exploring Grails Assets, Redirections, Secure Sockets Layer, and Chrome

Using Grails 2.1.1 with the resources plugin, I have encountered an issue when incorporating the jstree library which comes with themes configuration: "themes":{ "theme":"default", "dots":false, "icons":true } The JavaScript in the library locat ...

Merge arrays values with Object.assign function

I have a function that returns an object where the keys are strings and the values are arrays of strings: {"myType1": ["123"]} What I want to do is merge all the results it's returning. For example, if I have: {"myType1": ["123"]} {"myType2": ["45 ...

Issue with Angular's ngOnChanges Lifecycle Hook Preventing Function ExecutionWhen attempting to run a function within Angular's ngOn

In the midst of my evaluation process to ensure that specific values are properly transmitted from one component to another using Angular's custom Output() and EventEmitter(), I am encountering some issues. These values are being sent from the view of ...

Adsense ad unit is not responsive and fails to display properly at dimensions of 320x50 px

I have a unique banner ad that I want to display as the footer on my responsive website. Using media queries recommended in the advertising documentation, I am adjusting the size based on different screen widths. Check out the CSS code below: <style&g ...

Serve unique data to different bots and human visitors using express.js and node.js

I am looking for a method to differentiate between bot (such as google or bing) and human incoming requests, in order to provide tailored data to each. This could include serving json data for client-side javascript to build the site or preprocessed html. ...

ng-grid automatically resizing columns based on content width

I am currently utilizing AngularJS ng-grid and endeavoring to accomplish the following tasks: 1. Adjust column width dynamically based on the content within each column. 2. Automatically resize the last column to fill the remaining space when hiding column ...

Javascript cards arranged in descending order

I'm in the process of developing a sorting feature that arranges cards in the DOM from Z to A with the click of a button. Although I've successfully implemented the logic for sorting the array, I'm facing difficulties in rendering it. Withi ...

Chrome/IE displaying text indentation issue within nested divs

Encountering issues with nested divs in Chrome and IE, while Firefox works smoothly. The outer div has both text-indent and margin-top styles set. The inner div's display style is block, so the content after it should appear on a new line without any ...

Attempting to repair navigation menu on grou.ps website

Hey there, I'm currently working on improving the appearance of my website. The original site can be found at . After integrating it with the grou.ps community platform, I noticed that the navigation menu is not displaying correctly and the image is ...

"Using Mongoose to push objects into an array in a Node.js environment

I am faced with a peculiar issue involving an array of images in my code. Here is the structure: var newImageParams = [ { image_string: "hello", _type: "NORMAL" }, { image_string: "hello", _type: "NORMAL" } ] M ...

ajax event malfunction

My current issue involves an ajax event that is activated when I press the submit button to input data into a database. Originally, these elements were spread across separate files for testing purposes. Now that all the code has been consolidated, I have ...

Create a server directory structure that populates multiple HTML dropdown lists using either jQuery or AJAX

As a novice navigating jQuery and Ajax, I find myself faced with a specific challenge. My current situation involves a structured set of directories on a server. My goal is to populate a dropdown dynamically with this file hierarchy. Upon click ...

Is there a way to alter the CSS padding class for collapsed elements?

I've created a navbar by following Bootstrap's tutorial, but I'm facing an issue with the padding. I used the Bootstrap class "pe-5" to add padding to a form within the navbar so that it aligns to the right with some space from the screen ed ...

Discovering the screen width and increasing its value using CSS

Is there a way to determine the screen size and then add 253px to it? For example, in CSS: .element { width: calc(100% + 253px); } What would be the best approach to achieve this? ...

Enhancing user experience with AngularJS: Harnessing ng-Click for seamless task management on display pages

I'm struggling with my TodoList in AngularJS. I need help creating the ngClick function for the "addTodo" button. My goal is to send the entire form data to another page where I can display the tasks. Can someone guide me on what needs to be added to ...

Utilizing the HTML5 Download attribute for linking to external files

I am currently developing a web application for my own personal needs. One feature I would like to implement is the ability to set the download attribute on certain links. However, I have run into an issue where the files to be downloaded are hosted on ex ...

Why won't Node.js let me redirect to my error page?

I've been putting together my newsletter project with the Mailchimp API, everything seems to be working fine except for when I try to redirect to a failure page if the status code is not 200. The browser shows an error message saying 'localhost r ...

Incorporate JavaScript values into an HTML form to submit them to PHP

How can I successfully POST the values of 'vkey' and 'gene+varient' when submitting a form in HTML? The values are retrieved using JS code and displayed correctly on the form, but are not being sent upon submission. <form action="ac ...