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

The React Component is caught in a loop of continuous re-rendering and reloading

Just starting out with React and tackling my first project. Running into a bit of trouble here, so I'm sharing my code for some insight. When users input their search term and hit 'search,' they are redirected from another page to this one. ...

Limiting the rate at which a function can be executed in NodeJS

I am facing an issue where I need to create an interval of five seconds during which a function can be executed. The reason for this is because I am monitoring an Arduino serial port, which sends multiple signals when a button is pressed. However, in my no ...

The functionality of Bootstrap tooltips becomes disabled as soon as any element on the page is clicked

When initializing Bootstrap tooltips on my page, I follow this approach <script> $(document).ready(function () { $(function () { $('[data-toggle="tooltip"]').tooltip(); }); }); </script> A questio ...

encounter an auth/argument issue while using next-firebase-auth

Issues: Encountered an error while attempting to log in using Firebase Authentication. No errors occur when using the Firebase Auth emulator, but encountered errors without it. Received a 500 response from login API endpoint: {"error":"Unex ...

Can I insert JavaScript code in any location within an HTML file?

Typically, Javascript code is placed in the header section of HTML code. <head> <script type="text/javascript" language="javascript" src="core.js"></script> ... </head> However, I've tested putting Javascript code in the body ...

Utilize Vue's prop system to pass objects between components

Can you help with passing objects as props in Vue? It seems like a simple task, but I'm having some trouble. In my .vue file, I have the following code: <template> <div id="scatter"></div> </template> <script&g ...

Today's feature dish

I have scoured numerous tutorials online, but none of them seem to solve my issue. Currently, I have these buttons: <a href='faq.php'><div class='button'> <div class='button_top'> </div> <div class ...

Dealing with a JavaScript Problem on Wordpress Using AJAX

Struggling with transitioning a website from Drupal to WordPress, I encountered an issue with a page that utilizes AJAX. A user followed a tutorial on implementing AJAX using JavaScript, PHP, and MySQL. Even though the AJAX functionality works fine on Drup ...

The importance of utilizing local variables to securely store values passed from an Ajax call to a WCF method

Currently, I am experimenting with WCF and Jquery ajax for testing purposes. Although I am new to WCF, I encountered a problem with my "ProductsService" service that has four parameters being invoked from Jquery Ajax. Fortunately, I was able to resolve the ...

Encountered an npm compilation error - Unable to locate module: bootstrap-theme.css

I recently updated all the dependencies in my JavaScript program without making any changes to my components or index.js file. However, when I run npm run build I encounter an error with index.js related to bootstrap-theme.css: Failed to compile. Modul ...

Evaluation of Library (VueJS) - Displaying various components in an individual test case

Just starting out with testing and have a simple question: I am working on testing a checkbox component. I understand the basics, but how can I render multiple components within one it block? Here is my current code. I am stuck on the second test where I ...

Saving data in multiple collections using MongoDB and Node.js: A comprehensive guide

In a recent project of mine, I have implemented a combination of nodeJS and mongodb. My main goal is to store data in multiple collections using just one save button. Below is the code snippet that I am currently working with: var lastInsertId; loginDat ...

A dedicated folder for hosting the static assets generated by Nuxt.js

I have a quick question I'm looking to create a dedicated directory for the static files generated by Nuxt Js Currently, Nuxt Js compiles all files into a single directory called 'dist' As I am utilizing Django Server as my backend, I nee ...

Launching a modal in a new browser window with the help of JavaScript or PHP

I need to implement a feature where clicking a link opens a modal in a new tab and redirects the current page to a different link, similar to how retailmenot handles coupons. Here is the code snippet I am currently working with: <div onClick="myFunctio ...

Manipulate and scale with jQuery

I am currently utilizing the jQueryUI library with its Draggable and Resizable functionalities to resize and drag a div element. However, I am encountering some unexpected behavior where the div jumps outside of its container upon resizing. How can I resol ...

Implementing React inline styles by directly incorporating brackets into the HTML rendering

I'm working on a project in React using create-react-app and trying to apply an inline style. Based on my research, the following line of code should work fine: <div id="root" style={{ height: 'auto' }}></div> However, when I r ...

Datatables stands out by emphasizing rows across all paginated pages

Encountering an issue with the Datatables plugin when attempting to highlight rows on paginated pages beyond the first one. In the JavaScript code below, you can see where I have commented out adding the class info to all rows. When this is done and you n ...

Ways to retrieve targeted keyframes using JavaScript

Trying to access a scoped "keyframes" named move-left in JavaScript. How can I do this while keeping it scoped? Note that vue-loader will add a random hash to move-left, such as move-left-xxxxxxxxx. <template> <div :style="{animation: animati ...

How can I efficiently add multiple items to an array and store them in async storage using React Native?

I am trying to store multiple elements in local storage using React Native. I found some helpful documentation on how to do this here. Could someone guide me on the correct way to achieve this? Here's a snippet of my code: My current approach const ...

Identifying and locating white-colored text within an HTML document

My HTML file has the following structure: <HTML> <HEAD> <style> .secret { background-color: black; color: black; } </style> </HEAD> <BODY ...