Exploring the functionalities of jQuery and Local Storage: Understanding the Selector's various states

I am currently developing a new feature for font customization on a website. The drop-down menu offers several font options to choose from. When a user clicks on one of these options, the following code is executed:

jQuery(function($) {
if (localStorage.getItem('font-01')) {
    $('#font-css-01').prop('disabled', localStorage.getItem('font-01') == 'true');
}

$('#font-selector-01').on('click', function() {
    $('#font-css-01').prop('disabled', function(_, prop) {
        localStorage.setItem('font-01', !prop);
        return !prop;
    });
});
});

This script must be repeated for each font option, but I need to ensure that only one font choice is enabled at a time. Currently, there can be unexpected behavior if a user selects a non-default font and then chooses another non-default font (for example, selecting font-01 and then font-02). I need to figure out a way to reset previous choices before applying a new one.

The .prop() function targets the stylesheet ids for the different fonts, and each drop-down subitem is sequentially labeled from #font-selector-01 to $font-selector-n.

Answer №1

When using link tags, it is advised to utilize data-fid instead of id:

<link data-fid='01' href='...' rel='...' disabled>
<link data-fid='02' href='...' rel='...' disabled>

Ensure that they are disabled by default.
Assign class font-selector-c and include attribute data-fid='xx' to every li. Then implement the following code:

$('.font-selector-c').on('click', function() {
    var fid = $(this).data('fid')
    $('link[data-fid]').prop('disabled', true) // disable all the stylesheets
    $('link[data-fid="' + fid + '"]')
        .prop('disabled', false) // enable the required one
    localStorage.setItem('font', fid) // store the id of the chosen font
});
$('#font-selector-reset').on('click', function() {
    $('link[data-id]').prop('disabled', true) // disable all the stylesheets
    localStorage.setItem('font', null) // clear the saved id
});

// On initialization: retrieving user's selection
var c_fid = localStorage.getItem('font')
if (c_fid)
    $('link[data-fid="' + c_fid + '"]').prop('disabled', false)

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

Position this menu in the top left corner using HTML and CSS

Is there a way to position the vertical menu completely in the top-left corner without any margin? I've set all margins to 0 but there is still about 2px of space. Any ideas on how to fix this? Thank you in advance! ...

In search of a comprehensive demonstration of how to use JQuery/Ajax for pinging with success and failure detection

Given that the process is asynchronous with multiple requests happening in parallel, I would like a solution that can handle these requests and identify which success/failure corresponds to each specific request. I am considering utilizing the jqXHR Object ...

Exploring the framework and architecture of JSON, AJAX, PHP, and MySQL

I'm embarking on a new project and looking to incorporate ajax to fetch mysql results in json format for proper display using jQuery ajax. Being inexperienced with json, ajax, and jquery, I seek feedback on the adequacy of my design structure and any ...

Is it possible to transform the Bootstrap5 sidebar, currently positioned above the block content, into a sticky element on

After creating a Django blog using bootstrap5 and following guidance from the python crash-course book, I encountered an issue with my sidebar placement. Despite trying various methods, I struggled to "override" my blocks in order to keep my sidebar fixed ...

The location.reload function keeps reloading repeatedly. It should only reload once when clicked

Is there a way to reload a specific div container without using ajax when the client requests it? I attempted to refresh the page with the following code: $('li.status-item a').click(function() { window.location.href=window.location.href; ...

Sending serialized data via AJAX to a PHP controller using PDO

When a checkbox is checked or unchecked, an ajax call is triggered. As someone new to PDO MVC design, my goal is to pass serialized data to an object via the ajax call which then utilizes a function to store this data in the database. AJAX: $('#inte ...

The footer on my website refuses to stay in its designated

I have been searching online and tried the recommended solutions, but it seems like the footer is still overlapping my page. Does anyone know why this might be happening? footer { background: rgba(0, 0, 0, .93); I read on some forums that setting th ...

What is the best way to retrieve all files from a directory on a web server using jQuery?

By using only jQuery (without PHP), I have the following code: var url = "/repository/load/t3.case"; $.get(url, function (data, status, xhr) { console.log(xhr.responseText); }); This code allows me to retrieve a file from the web server. Howe ...

What is the best method for transferring form data to a string and storing it in localStorage effectively?

Is this the most efficient method for extracting form data into a string and storing it in localStorage? I developed this method independently, but I'm not an experienced programmer. It seems to work for my needs, but I'm unsure if it's com ...

I encountered an issue while using the tab bar feature in Bootstrap where I wasn't able to navigate back to the first tab or any

My current project involves JavaScript, and I integrated a Bootstrap tab bar component. However, when I try to run the code in Google Chrome, I encounter an issue. The first time I select the first tab, the content displays correctly. But when I select the ...

The width of a div element seems to mimic the width of the entire page inexplic

There is a page containing various div elements. HTML: <div class="utilitiesHeader"> <div id="utilitiesLogo"></div> <div id="utilitiesFIO">Name of user</div> </div> <div class="utilitiesContent"> <d ...

How can I populate a <select> tag with options dynamically using C# when the page loads?

I am using jQuery ajax to populate cascaded dropdown elements from a database. The issue I'm facing is that I can't seem to add the default "Select Program" option at the top of my first dropdown dynamically. Even though I tried using the prepend ...

"Enhance your website's loading speed with the Google Page Speed Up

Hi, I've been using the Google PageSpeed Module and have created a .htaccess file to optimize my website (www.anetoi.com). I tried using combine_css to merge my CSS files but it didn't work as expected. I followed Google's instructions but s ...

The CSS3 slideshow is displaying distorted and unfocused images

I have a CSS code that controls the timing of my slideshow with 3 images: .slideshow li:child(1) span { background-image: url(../../pic/bg1.jpg); } .slideshow li:child(2) span { background-image: url(../../pic/bg2.jpg); -webkit-animation-de ...

Extract the URL's name using jQuery

Looking for a way to extract the "step2" value from a given URL? Here's a JavaScript solution: const url = window.location.href; console.log(url); For example, let's consider this URL: http://www.myproject.com/wp/?edit_project=797#step2=projec ...

Arrange two divs next to each other on the page: the div on the right can be scrolled through, while the div on the

I am attempting to create a layout similar to this https://i.sstatic.net/Y1FCp.png My goal is to: Have two main divs positioned side by side inside a wrapper div Ensure the wrapper expands to fill 100% of the browser size The left div (banner) should b ...

Validating forms using Ajax in the Model-View-Controller

I am facing an issue with my Ajax form, where I need to trigger a JavaScript function on failure. The code snippet looks like this: using (Ajax.BeginForm("UpdateStages", new AjaxOptions { HttpMethod = "POST", OnSuccess = "refreshSearchResults(&apo ...

Jquery Issue: Safari Leaves Alert Messages Unclosed When Opening Next Alert

I am experiencing an issue in Safari Browser and need some help with the following scenarios (with Example). When I click a button to delete an account, an alert message pops up. This alert window has two actions - "OK" and "Cancel". If I click "OK", it r ...

What is the reason for the background image not appearing while utilizing a bootstrap template designed for it?

I recently started working on an asp.net application and decided to integrate a pre-made bootstrap template for the frontend. After some searching, I came across this one. The original site showcasing the template looked really appealing with a background ...

Bespoke animated angular material tabs

Having an issue with Angular Material tabs. I have managed to remove the "slide" effect, but I can't figure out how to modify or remove the black effect behind my tab. Can anyone offer some assistance? black effect 1 black effect 2 Here is a snippe ...