Updating padding through local storage does not function as intended

I recently added two buttons to my website for adjusting the padding. While they are functional, I find myself manually setting the padding for nav, main, and footer in the CSS. Here is the snippet of the code:

main {
    padding: 20px 25%;
}
footer {
    padding: 5px 25%;
}
nav {
    padding: 0 25%;
}
    var padding = 15;

    $('#paddingPlus').click(function() {
        switch(padding) {
            case 0:
                changePadding(5);
                padding = 5;
                break;
            case 5:
                changePadding(10);
                padding = 10;
                break;
            case 10:
                changePadding(15);
                padding = 15;
                break;
            case 15:
                changePadding(20);
                padding = 20;
                break;
            case 20:
                changePadding(25);
                padding = 25;
                break;
            case 25:
                changePadding(30);
                padding = 30;
                break;
            case 30:
                alert('You have reached the maximum amount of padding!');
                break;
        }
    });

    $('#paddingMinus').click(function() {
        switch(padding) {
            case 0:
                alert('You have reached the minimum amount of padding!');
                break;
            case 5:
                changePadding(0);
                padding = 0;
                break;
            case 10:
                changePadding(5);
                padding = 5;
                break;
            case 15:
                changePadding(10);
                padding = 10;
                break;
            case 20:
                changePadding(15);
                padding = 15;
                break;
            case 25:
                changePadding(20);
                padding = 20;
                break;
            case 30:
                changePadding(25);
                padding = 25;
                break;
        }
    });

    function changePadding(pad) {
        $('nav').css('padding', '0 ' + pad + '%');
        $('main').css('padding', '20px ' + pad + '%');
        $('footer').css('padding', '5px ' + pad + '%');
    }

I tried to implement local storage to save the padding settings, but it's not working and Chrome isn't showing any error messages. Here is that part of the code:

main { }
footer { }
nav { }
    switch(localStorage.getItem('padding')) {
        case 0:
            changePadding(0);
            localStorage.setItem('padding', 0);
            break;
        case 5:
            changePadding(5);
            localStorage.setItem('padding', 5);
            break;
        case 10:
            changePadding(10);
            localStorage.setItem('padding', 10);
            break;
        case 15:
            changePadding(15);
            localStorage.setItem('padding', 15);
            break;
        case 20:
            changePadding(20);
            localStorage.setItem('padding', 20);
            break;
        case 25:
            changePadding(25);
            localStorage.setItem('padding', 35);
            break;
        case 30:
            changePadding(30);
            localStorage.setItem('padding', 30);
            break;
        default:
            changePadding(15);
            localStorage.setItem('padding', 15);
    }

    $('#paddingPlus').click(function() {
        switch(localStorage.getItem('padding')) {
            case 0:
                changePadding(5);
                localStorage.setItem('padding', 5);
                break;
            case 5:
                changePadding(10);
                localStorage.setItem('padding', 10);
                break;
            case 10:
                changePadding(15);
                localStorage.setItem('padding', 15);
                break;
            case 15:
                changePadding(20);
                localStorage.setItem('padding', 20);
                break;
            case 20:
                changePadding(25);
                localStorage.setItem('padding', 25);
                break;
            case 25:
                changePadding(30);
                localStorage.setItem('padding', 30);
                break;
            case 30:
                alert('You have reached the maximum amount of padding!');
                break;
        }
    });

    $('#paddingMinus').click(function() {
        switch(localStorage.getItem('padding')) {
            case 0:
                alert('You have reached the minimum amount of padding!');
                break;
            case 5:
                changePadding(0);
                localStorage.setItem('padding', 0);
                break;
            case 10:
                changePadding(5);
                localStorage.setItem('padding', 5);
                break;
            case 15:
                changePadding(10);
                localStorage.setItem('padding', 10);
                break;
            case 20:
                changePadding(15);
                localStorage.setItem('padding', 15);
                break;
            case 25:
                changePadding(20);
                localStorage.setItem('padding', 20);
                break;
            case 30:
                changePadding(25);
                localStorage.setItem('padding', 25);
                break;
        }
    });

    function changePadding(pad) {
        $('nav').css('padding', '0 ' + pad + '%');
        $('main').css('padding', '20px ' + pad + '%');
        $('footer').css('padding', '5px ' + pad + '%');
    }

If someone could assist me in identifying where I'm going wrong, I would greatly appreciate it. Thanks in advance!

Answer №1

Building upon the earlier response, does this clarify things?

$('#paddingPlus').click(function() {
   let padding = parseInt(localStorage.getItem('padding'));
   if (padding >== 30) {
      alert('You have hit the maximum padding limit!');
   } else {
      padding += 5;
      changePadding(padding);
   }
}


$('#paddingMinus').click(function() {
   let padding = parseInt(localStorage.getItem('padding'));
   if (padding === 0) {
      alert('You have reached the minimum padding amount!');
   } else {
      padding -= 5;
      changePadding(padding);
   }
}

function changePadding(pad) {
        localStorage.setItem('padding', pad);
        $('nav').css('padding', '0 ' + pad + '%');
        $('main').css('padding', '20px ' + pad + '%');
        $('footer').css('padding', '5px ' + pad + '%');
}

Answer №2

Make sure to convert the padding retrieved from localStorage.getItem('padding') into a Number data type (such as

parseInt(localStorage.getItem('padding'))
). Since values retrieved from localstorage are returned as strings, using a case statement will not yield the desired result.

Answer №3

The issue arises from the conversion of a string to an integer with the pad value and the lack of updating the localStorage value in your second code snippet.

To address these issues and streamline the code, consider incrementing the value in each event handler instead of using a switch statement, and fetching the value from localStorage rather than depending on a global variable. Try this revised approach:

<nav>Navigation</nav>
<main>Main content</main>
<footer>Footer</footer>

<button class="padding" data-change="5">+</button>
<button class="padding" data-change="-5">-</button>
function setPadding(pad, change) {
  pad = pad == null ? 15 : parseInt(pad, 10);
  pad += (parseInt(change, 10) || 0);

  if (pad < 0) {
    alert('You have reached the minimum amount of padding!');
    return;
  }

  if (pad > 30) {
    alert('You have reached the maximum amount of padding!');
    return;
  }

  localStorage.setItem('padding', pad);
  $('nav').css('padding', '0 ' + pad + '%');
  $('main').css('padding', '20px ' + pad + '%');
  $('footer').css('padding', '5px ' + pad + '%');
}

// retrieve the value and apply it when the page loads
setPadding(localStorage.getItem('padding'));

// update the value when either button is clicked
$('.padding').click(function() {{
  setPadding(localStorage.getItem('padding'), this.dataset.change);
});

You can view a live demo of this solution on jsFiddle, as SO snippets do not have access to localStorage.

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

Obtain the option tag's name

One of my challenges is working with a dynamically created dropdown in HTML and having a dictionary in the back-end to retrieve keys. As users keep adding options to the dropdown, I face the issue of not having a value attribute like this: <option valu ...

How can you utilize jQuery to eliminate specific select field values from the DOM prior to submission?

I am currently working on a Squarespace form that utilizes jQuery to show/hide specific fields in order to create a customized form using the show(); and hide(); functions. $(".option2 select").hide(); The issue I am facing is that simply hiding the fiel ...

Enhance your Zara shopping experience with the dynamic image zoom-in

I am currently exploring ways to replicate the image zoom-in feature seen on Zara's product pages. To see this effect in action, visit their site: Upon clicking on the image, it opens up in a popup window where it is enlarged to fit the entire screen ...

Leveraging the power of JavaScript functions together with the asp:Timer component

<p><b> Progress: <asp:Label ID="progressPercentageLabel" runat="server"></asp:Label>%</b></p> <script> function updateBar() { var bar = document.getElementById("CompletionBar"); ...

Populating a Listview in jqueryMobile with dynamic elements

I am struggling with my listview. Whenever I try to add or remove items from the list, the jquery mobile styling does not get applied to the new content that is added. <ul data-role="listview" id="contributionList"> <li id="l1"><a>5. ...

Alternative to using the disabled attribute in JavaScript to make a checkbox read-only option

Does anyone know how to make a checkbox readonly so that its value can be submitted, while also disabling it? Using the disable attribute prevents the value from being submitted, and setting it as readonly doesn't seem to work for checkboxes. Your as ...

What is the best way to pass a JSON object from R to Plumber in a format that JavaScript can interpret as an array instead of

My goal is to receive a JSON raw response from R Plumber and then utilize it in Angular. However, I am encountering an issue where the JavaScript Framework is interpreting it as a string instead of recognizing it as JSON format. "[{\"id&bsol ...

What is the best way to arrange an unordered list in a horizontal layout?

I have four lists that I want to display side by side. The first row should show a Doctor and Patient side by side, the second row should show a Pharma Company and Employee side by side. However, in my code, this layout is not working as intended. .tree ...

Navigating between interfaces without the need to constantly refresh or reload

Currently, I am in the process of developing a website using ASP.NET MVC that allows users to navigate between pages without refreshing each time. My approach involves treating views as 'areas' or mini master pages, utilizing partial views inste ...

When moving from Babel version 5.8.35 to 6.0.0, be prepared for app.js to throw a SyntaxError and encounter an unexpected token during compilation

Currently, I am in the process of enhancing my ReactJS components using webpack. However, I have encountered a hurdle while trying to transition from babel version 5 to 6. Upon attempting the upgrade, it resulted in a stack trace error within my app.js cl ...

Show a specific div using jQuery fadeIn() when the user reaches the top of an HTML section

The code below has a specific purpose: 1) Determine the current scroll position. 2) Locate the parent article and determine its offsetTop for each .popup_next which represents a section on the site. 3) Calculate an offset value by adding 30px to the off ...

Understanding the lockfile: deciphering the significance of each line in the yarn.lock file

I'm curious about the meaning of each line in this file. I encountered issues with packages due to dependencies in my project. After upgrading nuxt from version 1x to 2x, all tests started failing. After spending hours searching online, I discovered ...

Generating several copies of an identical form using jQuery and HTML

While employing ASP.NET MVC, Partial Views, and Dialogs, I am making an ajax request to the server which returns a partial view. By using $('#elementTag').html(returnData) to refill the bounding divs, I encounter a situation where the returned pa ...

There appears to be an issue with the dynamic functionality of RouterLink in Angular 6

user-dashboard.html <ul class="nav flex-column"> <li class="nav-item"> <a class="nav-link" routerLink='/dashboard'>User Dashboard</a> </li> <li class="nav-item" *ngFor="let cat of categories; let i = in ...

I am facing issues connecting my Express Node server to my MongoDB database using Mongoose

Starting my backend journey, I keep encountering the same error with my server.js --> // Step 1 - Create a folder named backend // Step 2 - Run npm init -y // Step 3 - Open in VS Code // Step 4 - Install express using npm i express // Step 5 - Create serve ...

I encountered an issue with the onclick event in JavaScript

I have been struggling with an issue for some time now and I just can't seem to figure out what I am doing wrong. Here's the problem - when I click on a link on my website, a calculator should pop up. Then, when I click the off button on the calc ...

No internet connection detected - please check your connection and try again

In the scenario where the internet connection is not available, when the user clicks a button, an error message should be displayed using a dialog box. I attempted to use navigator.online in my Android mobile webview but it did not work. How can I show t ...

Utilizing HTML's multiple input type color feature to save selected colors directly to the database

I am currently using the input type color to select colors for customizing my site. I save the selected color to a database and then retrieve it to apply it to different areas of the site. This works well for a single input type color, but now I have mul ...

Tips for extracting JSON data from an API with identical names as values

I am working on a project to create a data search system using JSON. The JSON data is stored in a REST API, and the structure of the API is as follows: [ { "info": "cute but big animal", "type": "pig", ...

The default appearance of bootstrap-select appears to be flawed

Utilizing the amazing Bootstrap-select jQuery plugin has brought two unexpected default styles to my selectboxes. Despite inserting the necessary CSS and JS files into my website, all select boxes are displaying with these peculiar default settings (withou ...