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

Adjust the opacity of certain elements to be semi-transparent, with the exception of the one currently

I'm attempting to implement the :not selector in conjunction with :hover to create a visual effect where elements that are not being hovered over become semitransparent. My goal is as follows: 1) All elements start at 100% opacity 2) When an elemen ...

"Although getJSON is successfully returning values, the issue lies in these values not being added to

I am facing an issue with my getJSON request where it is returning the correct values but not adding them to the list Below is the code snippet: <script type="text/javascript> $(document).ready(function() { $("select#make").change(function(){ $(&a ...

Inverting Arrays Recursively with JavaScript

Currently, we are delving into functional JavaScript in my programming course with a particular assignment. However, I seem to be struggling to make the code work as intended. I would greatly appreciate any advice on how to improve this piece of code. Ever ...

Resetting input types with matching IDs inside a form is not possible using jQuery

I am having an issue with resetting a specific element using Jquery. I only want to reset the input fields where id=b, but when I place the reset button inside of <form>, it ends up resetting everything within the form. <script src="//ajax.goog ...

Updating the background-image using Jquery when a button is clicked

Is there a way to change the background image of a division using a button click without the need for a function? <input onclick="jQuery('#Div1').hide(); jQuery('#Div2').show(); jQuery('#main').css("background-image", "url ...

Problem with PHP file not properly inserting information from .ajax call into database

I'm relatively new to PHP and I have not yet worked with AJAX. After some research, I chose to utilize the Jquery .ajax function over the .post method because of its versatility and concise syntax compared to vanilla JavaScript. Below is the code for ...

Exploring the capabilities of TabrisJs in conjunction with Upnp technology

Working with Upnp in TabrisJs seems to be a bit challenging. Even though it has good support for node packages, I am facing difficulties while dealing with Upnp. I included node-upnp-client in my package.json file. "dependencies": { "tabris": "^2.0 ...

Using jQuery to submit data via POST method without having the page reload

I have a link in the footer that, when clicked, jumps to the header with a # in the address bar. Is there a way to prevent this and stay in the footer? Here is the code snippet: <a href="#" class="clickIn" id="1" attrIn="Like"><span style="color ...

Styling Labels with CSS Wildcard

I have been using the free NinjaForms plugin on my WordPress site. The default styling for labels is bold, but I prefer them to be lighter. Currently, I achieve this through CSS by targeting individual field IDs. However, this method becomes tedious when a ...

Download a complete website using PHP or HTML and save it for offline access

Is there a way to create a website with a textbox and save button, where entering a link saves the entire website like the 'save page' feature in Google Chrome? Can this be done using PHP or HTML? And is it possible to zip the site before downloa ...

How can information be transferred from a servlet to javascript in an Ajax program?

I am working on enhancing a simple jsp/servlet application by integrating AJAX functionality. Currently, I am utilizing JQuery for this purpose, but the choice of javascript framework is flexible. Here is an example of my code snippet: <script type=" ...

Coordinated Universal Time on the Website

I am currently developing a website that will be exclusively accessible through the intranet, but it targets users across Australia. Recently, I have been instructed to explore the idea of incorporating UTC time on the site. I am contemplating how I can i ...

What is the process for dynamically incorporating JavaScript files during compilation to serve as input for browserify?

Within our project's structure, there exists a directory housing multiple js files. The possibility of adding or removing these files later on is present. Currently, we have a file named main.js where each file is imported and a map is created (using ...

Encountering an error while trying to run the command "npm run start" due to an issue of "EMFILE

After running npm update, my project start broke. When I try to use npm run start, it returns the following error: 10% building 0/1 entries 0/0 dependencies 0/0 modulesnode:internal/errors:484 ErrorCaptureStackTrace(err); ^ Error: EMFILE: too many ...

What is the best way to retrieve the latest state after applying useEffect to trigger an onChange event for an element?

I am encountering an issue with an input field in my component that requires an onChange event to update the state. Despite binding the onChange event on mounting the component, the state remains unchanged as the onChange event seems to have the initial st ...

Having difficulty implementing getJSON function in CodeIgniter framework

My goal is to integrate AJAX calls into my website using codeigniter in order to receive live updates from the database. The click button function properly and displays all JSON data, however, I am facing an issue when trying to display a specific array a ...

Variety of perspectives on Magento products

Is there a way to configure Magento 1.7 to display view.phtml for bundled products and view.phtml for simple products, or the other way around? I am looking to customize the views for different product types - what is the best approach to achieve this? ...

JavaScript: protecting data, revealing functionality

Looking to enhance my understanding of Javascript basics in order to delve into client-side frameworks like Knockout and Angular, as well as make headway in learning Node.js. I've selected a simple problem used in teaching C# and am now attempting to ...

The response time feature appears to be malfunctioning within Mockjax

How can I simulate a long response time using Mockjax? Despite setting the responseTime to 20 seconds, my ajax call is still being executed immediately when the page loads. Any suggestions on how to fix this issue? To isolate potential sources of error, ...

Misaligned Div Content

Check out my jsfiddle here The text inside the <div> is shifting upwards Could someone explain why this is occurring? And suggest a solution? I would truly appreciate any assistance. Thank you! ...