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

Show all span elements in a map except for the last one

Within my ReactJS application, I have implemented a mapping function to iterate through an Object. In between each element generated from the mapping process, I am including a span containing a simple care symbol. The following code snippet demonstrates t ...

Tips for transforming the appearance of an asp.net page with asp:Content into a stylish css-page

Currently facing an issue where I am unable to change the background-color in my CSS file. As a workaround, I have placed the style directly within an ASP page. <asp:Content Id="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> ...

How to incorporate both image and text links within an HTML div container using JavaScript

I am trying to create a clickable image and text within a div named "films" that both link to the same webpage. However, I am experiencing an issue where only the text link works and the image link is disabled. If I remove the text link, then the image l ...

Jest encounters an error when a third-party function is invoked on a jQuery selector

I am experiencing an issue with my react component that is utilizing the dataTable() function from datatables.js on a jQuery selector. Even though I have set up a jest test component for testing, the tests are failing and throwing the following error. ● ...

The $scope object in Angular is supposed to display the $scope.data, but for some reason, when I attempt to access it

Having an issue with my controller that fetches data from a service. After receiving the data in the controller, I'm using $scope to pass it to the view. Strange behavior - console.logs inside the 'then' function display the data correctly ...

Incorporating PHP script within a stylesheet

Is it possible to include php code within a css file for adding conditions to css properties? styles.css <?php if($suserid == 2) { ?> .proverb { border:0px solid blue; margin-left:34px; width:250px !important; margin-top:6px; } <?php } e ...

Highlighting rows using jQuery upon selecting checkboxes

I attempted to emphasize a row in a table using jQuery when the checkbox is checked. This is the jQuery code I used for this purpose: $(":checkbox").change(function() { $(this).closest("tr").toggleClass("highlight", this.checked); }); However, it see ...

Can an action be activated when the mouse comes to a halt?

Currently, I am having trouble triggering an event when a user stops moving their mouse over a div element. The current event is set up to show and follow another element along with the mouse movement, but I want it to only display when the mouse stops mov ...

The intervals in hooks seem to be malfunctioning and not updating the date and time as expected

I am trying to continuously update the date and time every minute using React hooks. However, I am facing difficulty in updating the time properly. const Link = (props) => { let date = new Date(); const [dateTime, setDateTime] = useState({ cu ...

Utilizing NGINX as a reverse proxy for secure communication with Node.js

I'm currently running an NGINX server setup as a reverse-proxy server for a node application. I am now trying to enable HTTPS, but every time I attempt to access the site via HTTPS, I encounter a "502: Bad Gateway" error. server { listen 80; ...

Display or conceal section based on selected checkboxes

I'm currently working on a JavaScript script that involves showing/hiding elements based on radio button and checkbox selections. The goal is to reveal a hidden section when certain checkboxes are checked, as illustrated in the screenshot below: http ...

Show data from an API in an HTML table

I encountered an issue with an API, and despite trying console.log(response.[""0""].body) to view the response in the console, it does not seem to be working. My goal is to extract all the data from the API and display it in a table. Below is my code: ...

How can I show the number of items in my filtered data using AngularJS?

My data array holds objects in JSON format. var users = { 'New':{ {Name:'One'}, {Name:'Two'} }, 'Old':{ {Name:'Three'}, {Name:'Four'} } This piece of code is used to disp ...

What steps should I take to refresh my Partial View after a successful form submission?

Greetings, I hope this message finds you well. I have a help page on my website that includes an FAQ section (content served from a Web Service) and a button that displays a partial view. The partial view collects help request information and submits it to ...

React Native - The size of the placeholder dictates the height of a multiline input box

Issue: I am facing a problem with my text input. The placeholder can hold a maximum of 2000 characters, but when the user starts typing, the height of the text input does not automatically shrink back down. It seems like the height of the multiline text ...

What is the significance of Fawn's statement, "Invalid Condition"?

Despite following the instructions and initiating Fawn as stated in the document, I'm still encountering an error message that says Invalid Condition. Can anyone help me identify what is causing this issue? Thank you to all the helpers. await new Fawn ...

Assign the DatePicker Object to an HTML Element

I am currently using a SyncFusion date picker in my project and the implementation looks like this: var datepicker = null; $("#datepicker").hide(); $("#click").click(function(){ $("#datepicker").show(); datepicker = new ej.calendars.DatePi ...

Fill out a dropdown menu by selecting options from another dropdown menu

I'm currently working on populating a dropdown list based on the selection of another dropdown list. Here's what I have so far: Below is the function that takes the selected value from the first dropdown list as a parameter: [AcceptVerbs(HttpVe ...

Deploying a single node.js app on two separate servers and running them simultaneously

Is it possible to set up my game to run on both the west coast and east coast servers, while still using the same domain? In my code structure, app.js runs on the server with the home route serving as the entry point for the game. This means that users si ...

Elevate a div over another div

I have a situation where I need to nest two divs inside another div with the ID "video-wrapper". Here is the HTML code: <div class="row"> <div class="video-wrapper col-lg-2"> <div class="video-thumbnail"> <img ...