Verify if the value of localStorage matches the specified value, then conceal the element

This is my second query and I'm hoping it covers everything. My knowledge of javascript is limited, which has made it difficult for me to get my code working properly. Despite trying various different approaches, I have been unable to resolve the issue. The sections enclosed in brackets represent what I am aiming for but have not managed to implement successfully. To summarize:

- when button 1 is clicked: set localStorage.thing1 to 0

- when button 2 is clicked: set localStorage.thing1 to 1

- if localStorage.thing1 is equal to 0, hide thingtext1; otherwise, display thingtext1

<!DOCTYPE html>
<html>
<body>
<p id="thingtext1">Here Is Some Text</p>
<button id="thing1" onclick="(set value of thing1 as 0 in localStorage)">Hide</button>
<button id="thing1" onclick="(set value of thing1 as 1 in localStorage)">Show</button>

<script>
(ONLOAD)
if (localStorage.getItem("thing1") === "0") {
(HIDE(#thingtext1))
}
else{
if (localStorage.getItem("thing1") === "1"){
(SHOW(#thingtext1))
}
}
(SET thing1 into localStorage)
</script>

</body>
</html>

Your assistance in resolving this matter would be greatly appreciated. Thank you.

Answer №1

Give this a try:

<p id="text2">Some Unique Text</p>
<button id="uniqueButton" onClick="localStorage.setItem('uniqueItem', '0')">Hide</button>
<button id="uniqueButton" onClick="localStorage.setItem('uniqueItem', '1')">Show</button>

<script>
    $(function () {
      $(window).bind('storage', function (e) {
        if (localStorage.getItem("uniqueItem") == "0") {
            $("#text2").hide();
        }else if (localStorage.getItem("uniqueItem") == "1"){
            $("#text2").show();
        }
      });
    });
</script>

In the code above,

$(window).bind('storage', function (e) {

will run when there is a change in LocalStorage's value.

Answer №2

<p id="contenttext1">This is a Sample Message</p>
<button id="content1" onclick="saveData('0')">Hide</button>
<button id="content1" onclick="saveData('1')">Display</button>

<script type="text/javascript">
    function saveData(number){
        localStorage.setItem("content1", number);
        displayOrHide();
    }

    function displayOrHide(){
        if (localStorage.getItem("content1") == "0") {
            $("#contenttext1").hide();
        } else if (localStorage.getItem("content1") == "1"){
            $("#contenttext1").show();
        }
    }

    $(document).ready(function(){
        displayOrHide();
    });

</script>

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

JavaScript function for submitting form data using AJAX and performing validation

This is the code I have been working on: $(function () { $('.contact-form').submit(function (event) { $(this).find("input , textarea").each(function () { var input = $(this); if (input.val() == "") { ...

What is the best way to combine two JavaScript objects?

One object I am currently working with resembles the following structure let ob1 = { 'item_data':{ 'stack':{ 'purchase':'12345', 'order':'22222' } } } Additionally, I have anothe ...

Having trouble getting the jQuery autocomplete feature to function properly?

On my page, there is a button labeled "Add a Skill." Clicking on this button should trigger the display of an input box where you can enter your skill, another input box for your skill level, and a horizontal slider to select the skill level. In my databa ...

jQuery autocomplete function fails to run when embedded within a dynamically loaded AJAX form on a Ruby on

In my Rails application, I am loading a compose mail form by making an AJAX request. The code in my compose.js file looks like this: $('#main').html("<%= j render :partial =>"smails/form" %>"); When implementing an autocomplete fiel ...

Client-side filtering of events in FullCalendar

I found a helpful answer on Stack Overflow that I am trying to use for client-side event filtering. While it works perfectly for newer events, I am facing an issue with filtering events that are loaded from JSON. Below is my JavaScript code: $(document) ...

What would be the best way to create a JavaScript function that emulates the functionality of an Upgrade Button?

I am currently working on developing a clicker game and have reached the point where I need to implement a function for the 'upgrade click' button. This function should deduct a certain amount of money when clicked, while also increasing the amou ...

PNG file unable to display in Google Chrome

I created an image using paint.net and saved it as a .png file. However, when I try to display the image on my website, only the borders show up without any image content. Here is the code I used: HTML <a href="home.php"><img id="logo" src="../i ...

Issue with inner span not inheriting max-width set on outer <td> element

Whenever I hover over a table cell, the Angular Bootstrap popover should appear next to the text. However, the 'span' element remains at its full width. <td style="max-width: 50px; text-align: left; white-space:nowrap; overflow:hidden; text- ...

Cross platform compatibility in jQuery Ajax across different browsers and operating systems

Is there a specific explanation as to why a jQuery Ajax call to the server would function correctly on Firefox for Mac but encounter issues on Firefox for PC? ...

An unanticipated error occurred: Invalid invocation - line 41 of selector-engine.js

I recently updated my ASP.NET MVC application to the latest bootstrap and jQuery versions. When attempting to load a partial view in a modal, I encountered the following error: Error screenshot: https://i.sstatic.net/coAjF.png The modal window fails to ...

Issue with JS jQuery: The click event on an li element within an expanded ul does not function properly

I have built a basic webpage to explore jQuery. However, there is an issue that arises when I click on the "Button: another one." It seems to interfere with the event of clicking on the li element, causing it to glitch and not respond. Here is the code: JS ...

Goodbye.js reliance on lodash

In my search for the most lightweight and speedy jQuery implementation for server-side NodeJs, I've come across Cheerio as the best option. However, I've noticed that Cheerio has a code-size of around 2.6 MB, with approximately 1.4 MB attributed ...

Preventing the negative consequences of being colorblind through programming techniques

My experience as a web developer has taught me that poor color contrast on a website can severely impact revenue. I am determined to change this, but have encountered an issue. On my site, there is a section where users can select a color and see it displa ...

PhantomJS: Saving SVG for Future Use

I am attempting to save an SVG file from a sample testpage using PhantomJS. I have successfully navigated to the testpage, but I am unsure of how to locate and save the SVG element. Below is my current approach and where I am encountering difficulties. V ...

jQuery is attempting to create an animation by combining three variables to determine a new height

Currently, I am facing an issue with animating a div to a new height by summing up the heights of 3 other divs. Unfortunately, the heights do not seem to add up correctly, and I could really use some guidance on how to resolve this. Any suggestions or in ...

`Heart-shaped loading bar in Reactjs`

Looking for help in creating a heart-shaped progress loader for a React project. I attempted using CSS but encountered issues with the progress not filling the entire heart design. Below is the code snippet I used. The progress should start from the bottom ...

When using Angular2, I have found that I am unable to extract the body data from JSONP responses. However, I have discovered that this issue

Initially, I developed the SERVER using spring-boot framework. The code for this looks like: public class App { @RequestMapping("/") @ResponseBody String home(HttpServletRequest request) { String aa=request.getParameter("callback"); System.out.pri ...

Vue struggles to handle data coming from a composable function

For my specific case, I need to verify whether the user has subscribed to my product through both Stripe and Firebase. To accomplish this, I created a composable function that checks for the current subscription in the Firebase collection. If the user cur ...

Is it possible to determine if the user is able to navigate forward in browser history?

Is there a way to check if browser history exists using JavaScript? Specifically, I want to determine if the forward button is enabled or not Any ideas on how to achieve this? ...

"An error occurred stating that _co.JSON is not defined in

During my attempt to convert an object into a string using the JSON method, I encountered an error upon loading my page: Error: _co.JSON is undefined The stacktrace for this error message is extensive and seems unnecessary to include at this point. Th ...