Tips for recalling the display and concealment of a div element using cookies

My HTML code looks like this:

<div id='mainleft-content'>content is visible</div>
<div id="expand-hidden">Button Expand +</div>

To show/hide the divs, I am using JQuery as shown below:

 $(document).ready(function () {
    $("#expand-hidden").click(function () {
        $("#mainleft-content").toggle();
    });
});

I now want to utilize cookies to remember whether the div is hidden or shown based on user interaction.

Can someone guide me on how to achieve this? Thank you for your assistance.

You can also view it on JSFIDDLE

Answer №1

Click here for a working example

To check if a div is visible, you can use the is(":visible") function:

if ( $("#mainleft-content").is(":visible") ){
   alert('The div is visible');
}
else{
   alert('The div is hidden');
}

If you need to work with cookies, you can implement the following functions:

function setCookie(cookieName, cookieValue, expirationDays) {
    var expirationDate = new Date();
    expirationDate.setDate(expirationDate.getDate() + expirationDays);
    var formattedValue = escape(cookieValue) + ((expirationDays == null) ? "" : "; expires=" + expirationDate.toUTCString());
    document.cookie = cookieName + "=" + formattedValue;
}

function getCookie(cookieName) {
    var i, x, y, cookieArray = document.cookie.split(";");
    for (i = 0; i < cookieArray.length; i++) {
        x = cookieArray[i].substr(0, cookieArray[i].indexOf("="));
        y = cookieArray[i].substr(cookieArray[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == cookieName) {
            return unescape(y);
        }
    }
}

You can then set the cookie using the following code:

$(document).ready(function () {
    $("#expand-hidden").click(function () {
        $("#mainleft-content").toggle();
        SetCookie("DivStateVisible", $("#mainleft-content").is(":visible"),5);
    });
});

For managing cookies in jQuery, consider using the jQuery Cookie plugin available at this link:

function setCookie(cookieName, cookieValue, expirationDays) {
    $.cookie(cookieName, cookieValue, { expires : expirationDays });
}

function getCookie(cookieName) {
    return $.cookie(cookieName);
}

Answer №2

Utilizing the jQuery plugin available at http://plugins.jquery.com/cookie/

$(document).ready(function () {
    $("#mainleft-content").toggle(!!$.cookie("visible"));
    $("#expand-hidden").click(function () {
        $("#mainleft-content").toggle(function() { 
             $.cookie("visible", $("#mainleft-content").is(':visible') ? 1 : 0);
        });
    });
});

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

Customizing product prices with unique icons

I have successfully integrated a 'Latest Products' row on the Homepage of my WooCommerce enabled WordPress Website. Now, I am looking to enhance it by adding an icon on each side of the price entry. Although I know how to manually insert <i c ...

Issue with Dropzone not functioning correctly within Vue transition modal

I've implemented a dropzone function in the mounted function, which works perfectly when the dropzone is outside of a modal in the view. However, when I try to use it within a modal with a transition effect, it doesn't work. Any suggestions on ho ...

Position the table at the bottom of the page using CSS

I'm experiencing an issue where my HTML is not rendering correctly. I need to move the table with the ID "footer" to the bottom of the page. Here's the structure of the situation: <div id="container"> <table id="footer"></tabl ...

I am able to successfully receive accurate data in JSON format, however I am facing difficulties binding it to a jquery

I am struggling with integrating data fetched in JSON format using $.ajax into a table using jquery's datatable. Below is the JavaScript code I have been trying: $(document).ready(function () { $.ajax({ type: "POST", url: "Result.aspx/getUser ...

lint-staged executes various commands based on the specific folder

Within my project folder, I have organized the structure with two subfolders: frontend and backend to contain their respective codebases. Here is how the root folder is set up: - backend - package.json - other backend code files - frontend - p ...

Selecting the current date in a Jquery Datepicker using PHPUnit WebDriver Selenium and PHP

Check out this demo of our datepicker: ( Located in the bottom left corner ) $search21 = $this->webDriver->findElement(WebDriverBy::id('csandbox-container')); $search21->click(); // Clicking opens the datepicker. // Now, how do I ...

Issue with div not updating after successful ajax request, troubleshoots fine on initial request but not subsequent ones

I have coded a livesearch feature in my header.php file. This livesearch functionality includes an 'Add to Cart' button for users to easily add products directly from the search results. Additionally, I have a Cart section in the header where the ...

Display items in a not predetermined order

Despite its simplicity, I am struggling to get this working. My aim is to create a quiz program using JavaScript. Here is the basic structure: <ul> <li>option1</li> <li>option2</li> <li>option3</li> </ul> &l ...

The visibility of JavaScript script to Tomcat is obscured

Working on a web project using servlets and JSP in IntelliJ. One of the JSP files manages graphics and user forms with graphics.js handling graphics and form validation done by validator.js. The issue I'm facing is that while Tomcat can locate graphi ...

Ways to achieve text transparency with CSS without converting it to an image

Is there a way to have my navigation bar indicate the selected page by changing the text color and adding a black background, while making only the text inside the current page nav transparent? For example, you can see the effect here: sammarchant.co.uk/n ...

Is it possible to configure Cypress to always open in the current tab instead of opening in a new tab?

One challenge with Cypress is testing on multiple tabs. Our website default to opening in a new tab. Is there a way to make Cypress continue the tests on the same tab? cy.get(element).invoke('attr', 'target', '_self').click() ...

Exploring the power of Jquery's id selector in Javascript

Recently, I came across a unique approach to using the ID selector in jQuery: $("*[id*=foo]").val() I'm curious about why this method is being used and how it compares to the standard id selector in jQuery. What sets this implementation apart from t ...

Array of dynamically typed objects in Typescript

Hello, I am a newbie to Typescript and I recently encountered an issue that has left me stumped. The problem I am facing involves feeding data to a Dygraph chart which requires data in the format [Date, number, number,...]. However, the API I am using prov ...

Launching an online platform with Express and Ember frameworks

I am embarking on a project to create a straightforward CMS using Node.js (with Express) and Ember.js. While I have experience with Angular, I am new to Ember.js. I've noticed that Ember.js operates similarly to Angular in terms of its CLI reliance, a ...

Creating Dynamic Videos with PHP and HTML

Trying to display the user-submitted video, but all my attempts failed for some reason: 1. echo "<video width='500px'>"; echo "<source type='video/mp4' src=$var autoplay>"; echo "</video>"; echo "<video width=& ...

Having issues with validating a form using Yup for a Checkbox input?

My form is built using mui, formik, and yup. If the input fields are empty (e.g. "surname") after clicking the submit button, an error is displayed. However, the issue arises when the checkbox for Terms of Service isn't checked as no error shows up. ...

"Unleashing the Power of MongoDB's Dynamic $in

Is there a way to dynamically pass a list of strings to a $in clause in MongoDB? I attempted the following code, but it didn't work and I haven't been able to locate more information other than an example with hardcoded values. The restrictedUs ...

The display is not appearing

In my JavaScript code, I invoked an ActionResult like this: function checkSessionNewContribute(){ if (@MountainBooks.Common.ProjectSession.UserID != 0) { window.location.href = "../Book/ContributeNewBook" } else{ $.ajax({ ...

Can you explain the concept of an anonymous block in JavaScript ES6 to me?

Recently, I came across an article on pragmatists which discussed some interesting ES6 features. However, one concept that caught my attention was the use of an anonymous block within a function. function f() { var x = 1 let y = 2 const z = 3 { ...

Leveraging IE conditional comments for including CSS or JavaScript files can lead to an increase in the number of HTTP

Our web designer has implemented special pages for Internet Explorer by using IE-specific comments. This means that certain stylesheets are only loaded if the user is using a specific version of IE: <!--[if lt IE 7]> <link type="text/css" rel="st ...