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

Utilize v-for to dynamically showcase a variety of images on your

My goal is to showcase several JPG pictures located in the src/assets/images folder by utilizing the v-for directive. However, it seems like the browser is having trouble locating them. Interestingly, manually adding the pictures with the same paths works ...

The dimensions of a Tumblr video

Hi there! I have a question regarding my tumblr theme. The space allocated for video posts on the home page is perfect, but when I click on the permalink, it becomes too small. I don't want to change the size of the video on the home page, so is there ...

Troubleshooting a malfunctioning filter in Moongose for a Referenced Entity

I am dealing with two main Entities called Organization and Applications. A single organization has the capability to possess multiple Applications. const organization = mongoose.Schema( { name: { type: String, required: ...

Nightwatch.js feature not functioning properly in a 'closing' manner

I'm facing an issue where I need to execute a function at the beginning of my test before proceeding with the rest of the test steps. Here is the custom command I am using, named internalAdviceLinksHtml: const solr = require('solr-client') ...

Is it possible to load Angular.js without any references?

In the process of reverse engineering a User Interface that is operational but has a few bugs. Created using HTML, CSS, and JavaScript with data acquired through a REST API. The interface is designed for a Windows environment. While examining the index.ht ...

Issue with switching button and content positioned absolutely

Within this container, I have some content followed by a slide toggle button and then more content. The toggle button utilizes the jQuery function slideToggle. All elements within are positioned absolutely. [Introduction Content] Toggle Button [Hidden C ...

Error: Trying to access the 'title' property of an undefined variable in Vue.js

Creating a replica of hackernews by utilizing the axios API. The NewItem.vue component is not receiving any data, resulting in an error — TypeError: Cannot read property 'title' of undefined. Can you identify what's causing this issue in t ...

Using jQuery AJAX to send data containing symbols

When making an AJAX call, I am including multiple values in the data like this: var postData = "aid="+aid+"&lid="+lid+"&token="+token+"&count="+count+"&license="+license; postData = postData + "&category="+category+"&event_name="+e ...

Using Next.js for dynamic routing with JSON arrays in getStaticPaths

I am currently facing an issue while trying to incorporate a json file with multiple arrays into my Next.js application. The structure of the json file is quite complex, and I'm unsure about how to convert it into a format that can be effectively util ...

jQuery function not executing after subsequent AJAX request

Can anyone provide some assistance with my AJAX/jQuery setup? I'm attempting to dynamically load code into a jQuery Dialog. There is some jQuery code within the content that initializes buttons and loads tabs. The issue I'm facing is that the c ...

What is causing lxml to not remove section tags?

Having some trouble parsing HTML using lxml and Python. My goal is to eliminate section tags, but seems like lxml can remove other specified tags except for sections. For instance: test_html = '<section> <header> Test header </header& ...

Tips for utilizing jquery.load for fetching a section of an html document or an entire html file

I'm experimenting with jquery's load function to dynamically fetch and display HTML content, rather than using $.ajax(). I enjoy exploring the various features that jQuery offers and want to understand how each one works. Below is the code I am ...

Can users arrange a lineup of choices?

As a beginner, I have a task that seems pretty simple to others but not so much for me. I need to create a feature where a client can order 10 different services in the order they prefer. The idea is to use a dropdown menu or checkboxes to allow the user ...

Utilize the composition API in Vue.js 3 to call a function and pass in a parameter

I'm having trouble calling a function from another component. When I click on a button in my parent component, formTelemarketing(), it should send data to my other component nAsignedCalls() and call the function getCalls(param) in that component. Thi ...

Tips for displaying a success message in a session variable with the jQuery.get() function

Currently, I am using jQuery.get() to delete a row from a table on the page main.php. After deleting the row, I would like to display a success message which should be stored in a session variable ($_SESSION['successMsg']). How can I set a succ ...

The CSS Grid does not align properly in the horizontal direction when displayed on mobile devices

I am currently working on a responsive layout where the header and footer should each take up around 5% of the screen space and remain fixed. The middle section should scroll based on the number of elements within it. Despite using the fr and % values, the ...

Javascript enables the magnetization of cursor movements

Can a web page be designed so that when users open it and hover their mouse over a specific area outside of an image, the mouse is attracted to the image as if by a magnet? Is this idea feasible? Any suggestions would be appreciated. ...

The Express application fails to receive a response from a Mongodb query function

In my current project, I am implementing a simple API Key authentication system. The main goal is to validate the provided key against the user's input. There is a separate file containing a function that queries the database and returns either true/ ...

Error code 0 occurs in jQuery AJAX when there is an issue with the communication between the client

Currently delving into the world of ASP.NET and wanted to create a basic website utilizing ajax to retrieve a simple string from the server. Upon running the ajax request, an error message pops up stating An error occurred: 0 error Here's a glimpse ...

Synchronous AJAX requests do not function properly in IE and Firefox, but they do work in Chrome and Safari

Attempting to measure download speed using an AJAX call. Below is the code snippet: var start = new Date(); $.ajax ({ url: 'https://www.example.com/perftest/dummyFile1024', cache: false, success : function() { var total = ( ...