Preserve present condition following a jQuery click event

I'm facing a challenge where I need to hide a button upon clicking another button, but the problem is that when the page refreshes, the hidden button becomes visible again. My objective is to keep it hidden even after refreshing the page and only reveal it when the show button is clicked. Any assistance with this matter would be greatly appreciated.

Here's the HTML code:

<button type="button" class="showhide">Show / Hide</button>
<button type="button" class="link">Link</button>

And here's the JavaScript code:

$('.showhide').click(function(){
 $('.link').hide();
});

Answer №1

As @JohnDoe suggested, implementing a local storage solution will solve the issue.

To accomplish this, simply set the localStorage value when the button is clicked. Then, on page load, you can check the localStorage value to determine whether the button should be visible or not.

$('.showhide').click(function(){
    $('.link').toggle();

    var isVisible = $('.link').is(":visible"); 
    localStorage.setItem('visibility', isVisible);
});

// Since `toggle` requires a boolean value and localStorage stores values as strings
var isVisible = localStorage.getItem('visibility') === 'false' ? false : true;
$('.link').toggle(isVisible);

You can find a working example of this implementation here: https://jsfiddle.net/1m3rnj2b/

Answer №2

To manage this, you can utilize the power of browser storage. Consider implementing the following code snippet on the client-side using localStorage or alternatively, if it suits your needs, use sessionStorage in your server script.

if(localStorage.getItem('isHidden')) {
  $('.link').hide();
}

$('.showHideButton').click(function(){
  $('.link').hide();
  localStorage.setItem('isHidden', true);
});

Answer №3

To maintain the button's hidden state even after closing the browser, you should consider utilizing localStorage. You can find more information on this feature here. Alternatively, if you prefer a session-based approach where data is cleared upon closing the browser, I would recommend using sessionStorage. More details about session storage can be found here.

In order to achieve this functionality, two essential functions need to be utilized: getItem and setItem. Here's an example demonstrating their usage with sessionStorage, but it can also be applied to localStorage:

$(document).ready(function(){
    if(sessionStorage.getItem('isButtonHidden')){
        $('.link').hide();
    }

    $('.link').click(function(){
        $('.link').hide();
        sessionStorage.setItem('isButtonHidden', true);
    });
});

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

Error encountered in Ubuntu while attempting to run a Python script within a Node.js/Express application: spawn EACCES

Recently, I set up a node.js server to run a python script using the python-shell . However, after migrating from Windows to Ubuntu, an EACCES error has been persistently popping up. Despite my attempts to adjust permissions and troubleshoot, I haven' ...

Utilizing PHP and Ajax to showcase individual row details within a while loop upon clicking a hyperlink

In the midst of a new project, I find myself faced with a task where the user can log in and view their personal delivery orders. The list of deliveries is generated using a while loop. However, whenever I click on the details button for an item in the lis ...

Is it possible to alter preact-material-components to switch to mdc-theme--dark mode, thereby changing the CSS style of all descendant components?

I recently created a preact-cli app and added the following code in Header.js: document.body.classList.add('mdc-theme--dark'); However, when a user tries to switch from the light theme to the dark theme, only the background of the app changes. ...

The return value from vue-query is ObjectRefImpl, not the actual data

Greetings to the Vue.js community! As a newcomer to Vue.js, I am seeking guidance on fetching data using vue-query, Vue.js 3, and the composition API. The data returned to me is ObjectRefImpl, but when I try to print the values, I encounter the error: "Pro ...

Using React and Material-UI to dynamically populate a table with data retrieved from

Material ui table utilizes data in a specific format. rows: [ createData(1, "dashboard", "details"), createData(2, "product", "product details"), ].sort((a, b) => (a.id < b.id ? -1 : 1)) When the API responds with data stored in st ...

Footer positioned centrally on screen

My webpage footer seems to be misplaced, appearing in the middle of my content instead of at the bottom where it should be. Surprisingly, the code for the footer works perfectly on other pages. Any suggestions on why this might be happening? I've sco ...

Sketch a variety of numerical values in a circular formation

I was working on a number circle using the below fiddle, but I need it to always start from 0 at the top. How can I achieve this? Additionally, I would like to connect the numbers from the inner circle border to the number with a dotted line. How can I dr ...

The "hover" effect is not activating on a carousel

I'm having trouble with the hover effect inside the orbit slider. It's not working at all. What am I missing here? Check out the code and fiddle: http://jsfiddle.net/Bonomi/KgndE/ This is the HTML: <div class="row"> <div class="la ...

Efficiently generating and managing numerous toggle buttons in Reactjs with Material-ui ToggleButtons

Currently, I am exploring the idea of designing a sidebar that incorporates a variable number of toggle buttons generated from an object containing keys and values. However, I am encountering difficulties in utilizing the "key" value to adjust the corres ...

Utilizing the closest method to retrieve the form element

As I review code written by another developer, I came across a surprising method used to retrieve a form object. HTML for Login Form <form id="frm_login" action=""> <input type="text" name="username" id="username"> <input type="passwor ...

Unusual Actions from the Text Field

Please take a look at this link <div id="textarea_wrapper"> <textarea>How and where is my width derived from?</textarea> </div> #textarea_wrapper{ height: 250px; border:thick solid green; } textarea{ background-color: #930; ...

What is the most effective method for preserving RichText (WYSIWYG output)?

I am currently using a JavaScript-based rich text editor in my application. Could you suggest the most secure method to store the generated tags? My database is MySQL, and I have concerns about the safety of using mysql_real_escape_string($text);. ...

The text sliding feature gradually moves further away from the left side with each iteration

I am in the process of transferring an existing slider from one website to another. Instead of creating a text slider from scratch, I decided to modify the code I found for the new site. However, the slider is not functioning correctly on the new site. Th ...

What is the best way to convert a Date into the JSON format before sending it to the database?

I'm currently delving into backend development with Node.js, and I am in the process of connecting my backend to a MongoDB. Specifically, I am working on creating a User object that includes Birth Date as one of its properties. However, I am strugglin ...

When using React hooks forms, setting default values from a reduced array does not automatically populate the form. However, manually entering the same object into the form does

As I work with react hooks forms, I am facing a challenge in setting default values for a form generated by mapping over an array to output the inputs. After reducing the array into an object format like {name0:"fijs",name1:"3838"...}, manually passing thi ...

Error: The column 'joinedactivities.searchact id = searchact.id' is not recognized in the 'on clause'

I keep encountering this particular error: Error: Unknown column 'joinedactivities.searchact id = searchact.id' in the 'on clause'. I have meticulously inspected the table names and even attempted to make modifications, but multiple err ...

Bringing in functions - NodeJS - non-HTML

Currently, I am in the process of learning automation for my job and have hit a roadblock. In times like these, stackoverflow has proven to be a life-saving resource :) My current task involves writing a Selenium test in VisualStudio using JavaScript (nod ...

Creating HTML code from a template using different programs

Currently, I am in the process of developing a website using only HTML, CSS, and JS without the need for a backend. It is a straightforward site designed for presenting information. Each page follows a standard template consisting of a header, content area ...

Does aoMap function exclusively with THREE.BufferGeometry?

Can you provide guidance on setting up an aoMap for a standard THREE.Geometry object? Is there a demo available to reference? var uvCoordinates = geometry.attributes.uv.array; geometry.addAttribute('uv2', new THREE.BufferAttribute(uvCoordina ...

Clicking on a button in the Shield UI Grid Toolbar will apply filters to

Currently, I am working with a grid that utilizes a template for the toolbar. In this grid, there is a column labeled "Status." My goal is to filter the rows so that only those where the Status equals Request to Reschedule, Cancelled, Office Call Required, ...