What is the best way to make a JavaScript cookie remember the state of a DIV?

Seeking assistance with a test site here that is currently in development. I am attempting to make the notification at the top remain hidden once the close button is clicked.

Below is my current script:

<style type="text/css">
<!--
.hide {
display:none;
}
.show {
display:block;
}
-->
</style>

<script type="text/javascript><!--
var state;
window.onload=function() {
obj=document.getElementById('alert');
state=(state==null)?'show':state;
obj.className=state;

document.getElementById('close').onclick=function() {
obj.className=(obj.className=='show')?'hide':'show';
state=obj.className;
setCookie();
return false;
}
}

function setCookie() {
exp=new Date();
plusMonth=exp.getTime()+(31*24*60*60*1000);
exp.setTime(plusMonth);
document.cookie='State='+state+';expires='+exp.toGMTString();
}

function readCookie() {
if(document.cookie) {
state=document.cookie.split('State=')[1];
}
}
readCookie();
//-->
</script>

and then:

<div id="alert" class="show" style="float: left; width: 100%;"><div style="width: 80%; text-align:left; float:left;">Apologies for the recent downtime, we were experiencing issues with our web host. Everything should be resolved now =D</div> 
<div style="width: 18%; text-align:right; float:left; padding-right: 20px;"><a href='#' id="close">close</a></div> </div>

However, it is not functioning as expected. Any suggestions or solutions are appreciated!

Thank you,

Sam

Answer №1

To start, make sure to correct the readCookie function. The split in your current code will only capture what comes after "State=", which is then stored in the first element of the resulting array. To rectify this issue, adjust your script as follows:

function readCookie() {
    if(document.cookie) {
        var temp = document.cookie.split(';')[0];
        state = temp.split('=')[1];
        alert(state);
    }
}

Answer №2

In my experience, it actually functions properly (Firefox 3.5, Windows XP). However, the div element doesn't vanish until the entire site has completed loading. One possible solution could be to initially hide the div by setting its style attribute to display:none and then making it visible after the page finishes loading.

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

Contact a relaxation service periodically to pause its operation

To continuously check the status of a webservice, I need to make a REST call every x seconds (3000 ms) until the desired result is obtained or until it has been attempted 12 times. The call should also stop once the expected status is received: function m ...

Header element placement problem

After collaborating with fellow members of this community, we successfully developed this code. The issue at hand: Struggling to position headers below the social buttons in the center of the page after a div element. Here's the link to the Fiddle f ...

Ways to retrieve text like innerText that functions across all web browsers

I need to retrieve the text from a Twitter Follow button, like on https://twitter.com/Google/followers Using document.getElementsByClassName("user-actions-follow-button js-follow-btn follow-button")[0].innerText correctly displays the text as: Follow ...

Checking if children have certain text using jQuery

My task involves filtering an HTML table. In order to accomplish this, I have created an 'each' callback for all 'tr' elements and check if any of their children contain a specific pattern. $("#filter").keypress(function() { var fi ...

Touchwipe incorporation - single-page website script

Today has been dedicated to troubleshooting and searching for a solution regarding the integration of TouchWipe () on a custom one-page-site script based on Parallax that I found perfect for my latest project (). The script itself performs beautifully wit ...

Blurry black-and-white picture

As a beginner in HTML and CSS, I am still learning. I have a challenge where I have two images and when one of them is hovered over, it should increase in size and display text. Additionally, I want the image that is not in focus to appear in grayscale. Wh ...

Designing templates for websites and applications using node.js

Simplified Question: As I delve into improving my skills with node.js, I'm exploring the concept of templating. How would using node to serve one HTML file and loading page-specific information through AJAX/sockets impact performance and design princ ...

Troubleshooting challenges arise with Bootstrap's button group spacing issue

I am encountering spacing issues with the markup provided below. <h2>Profitability Report</h2> <form method="post"> <div class="row"> <div class="col-md-12"> <div class="btn-group btn-group-toggle ...

Error: Disappearing textarea textContent in HTML/TS occurs when creating a new textarea or clicking a button

I've encountered an issue with my HTML page that consists of several textareas. I have a function in place to dynamically add additional textareas using document.getElementById("textAreas").innerHTML += '<textarea class="textArea"></text ...

Using ng-if in AngularJS to compare two objects

I am transferring between controllers with different formations, and I am attempting to use "ng if" to compare the ids, but it is not functioning as expected. Below is the code snippet: var postsApi = 'http://mywebsite.com/wp-json/posts?filter[p ...

How can I adjust the border opacity in a React application?

Can we adjust the border color opacity in React when using a theme color that is imported? For example, if our CSS includes: borderBottomColor: theme.palette.primary.main and we are importing the theme with Material UI using makeStyles, is there a way to ...

Ways to Toggle div Visibility for Elements with Identical Class Names on an Individual Basis

After searching for solutions on stackoverflow, I attempted to implement some answers provided by other users, but I'm still not achieving the desired outcome. In my website's about section, there are four different items. When a specific item&a ...

A Promise-based value returned by a Typescript decorator with universal methods

I am currently working on creating a method decorator that can be applied to both prototype and instance methods. Referenced from: Typescript decorators not working with arrow functions In the code provided below, the instanceMethod() is returning a Prom ...

Troublesome behavior from Bootstrap's datepicker

Recently, I decided to dive into front-end development using Bootstrap but I'm facing some challenges. There are two issues here. The calendar glyph is appearing under the date input field instead of at the end of it on the same line. The picker is ...

Is there a reason why the JSX select element does not automatically select the option (implementing 'selected')? I'm unsure if I am overlooking something

In my HTML, I have a snippet of code that defines a custom <SelectField> component using a <select> tag like this: export default function SelectField(props) { /* PARAMETERS: - fieldname (String) - fieldID (String) - options (A ...

Implementing AngularJS html5mode alongside nodeJS and Express

Currently, my AngularJS application is being served by a nodeJS server with Express. Everything runs smoothly when using the default angularJS routes (hashbangs); however, I am now attempting to enable html5 mode. To activate html5mode, I have implemented ...

The mesmerizing world of Vue templates and transition groups

My previous simple list had transitions working perfectly, but now that I am using components and templates the transitions no longer work. Can anyone help me understand why? I want each item to animate individually, but it seems like all items are transi ...

The feature of Google street view is not supported within the tabs on WordPress

I'm experiencing some issues with displaying Google maps and street view using the Wp Google Map WordPress plugin within tabs. The map displays perfectly on the first tab where I placed the short code for the map, but on the second tab where I placed ...

Is it possible to manually disrupt the predetermined prototype chain of Numbers, Strings, Booleans, and Arrays in JavaScript, or reassign values to do so?

Whenever we create a new variable of the number type (let's say num1), its __proto__ is set to point to the Number Object. The __proto__ of this points to Object Core, and its __proto__ ultimately ends with null, completing the Prototype chain. My go ...

Choose the child nodes upon selecting the root node

I am trying to implement a 2-level material-ui treeview where selecting the root node should automatically select all child nodes as well. Does anyone have suggestions on how to achieve this with material-ui treeview? For more information, please visit ma ...