Keep track of the toggled state and prevent any flickering when the page is reloaded, all without the

After extensive searching, I couldn't find exactly what I needed. Therefore, I decided to utilize cookies to remember the toggled state of a div whether it's hidden or visible. However, I encountered an issue where there is flicker happening as the div transitions from its default state to the state based on the cookie when a page refresh occurs or when navigating to a different link. My task now is to investigate if there is a way to eliminate this flicker without using server-side code.

Below is the HTML structure:

<html>

<head>
  <title></title>
  <meta name="charset" content="utf-8" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
  <script src="app.js"></script>
  <! -- getCookie() and setCookie() are loaded from app.js -->
</head>

<body>
  <nav>
    <ul class="list-unstyled">
      <li class="active"><a href="index.php">Home</a></li>
      <li><a href="about.php">About</a></li>
    </ul>
  </nav>
  <a href="#" class="buttonCollapse" id="btn-close"><span class="arrow">&laquo;</span>  </a>
  <a href="#" class="buttonCollapse-open" id="btn-open"> <span class="arrow">&raquo;</span> </a>
  <div class="container side-nav">
    <h1>SideBar that has to hide on click</h1>
  </div>
  <div id="wrapper" class="main">
    <h1>Main Content</h1>
  </div>
</body>

</html>

Here is the corresponding CSS:

body {
  position: relative;
}

.container {
  margin: 20px 20px;
  width: 200px;
  height: 500px;
  background: #ccc;
  display: inline-block;
}

.hideSideNav .side-nav {
  display: none;
}

.hideSideNav #wrapper {
  padding-left: 20px;
}

.main {
  width: 500px;
  height: auto;
  background-color: #f9f9f9;
  display: inline-block;
  position: relative;
  margin: 0 auto;
}

.buttonCollapse {
  font-size: : 25px;
  text-decoration: none;
  position: absolute;
  left: 200px;
  margin-right: 7px;
  margin-top: 5px;
  z-index: 10000;
  opacity: 1;
  text-decoration: none;
}

.buttonCollapse-open {
  font-size: : 25px;
  text-decoration: none;
  position: absolute;
  left: 20px;
  top: 30px;
  z-index: 10000;
  display: none;
}

.buttonCollapse:hover,
.buttonCollapse-open:hover {
  text-decoration: none;
}

span.arrow {
  font-size: 25px;
}

Lastly, here are the getCookie(), setCookie(), and deleteCookie() functions for your reference, sourced from app.js:

function setCookie(name, value, expires, path, domain, secure) {
  document.cookie = name + "=" + escape(value) +
    ((expires) ? "; expires=" + expires.toUTCString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else {
    begin += 2;
  }
  var end = document.cookie.indexOf(";", begin);
  if (end == -1) {
    end = dc.length;
  }
  return unescape(dc.substring(begin + prefix.length, end));
}

function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

Additionally, below is my JavaScript code which I load in a script tag immediately after the body tag:

if (localStorage.getItem('State')) {
document.body.classList.add('hideSideNav');
} else {
document.body.classList.remove('hideSideNav');
}

And here is the remaining JavaScript logic:

var btnOpen = "btn-open";
var btnClose = "btn-close";

function showElement(elemid) {
if (elemid != null) {
document.getElementById(elemid).style.display = "inline-block";
if (elemid == btnClose) {
document.getElementById(btnOpen).style.display = "none";
document.body.classList.remove('hideSideNav');
[0].classList.remove('hideSideNav');
} else if (elemid == btnOpen) {
document.getElementById(btnClose).style.display = "none";
document.body.classList.add('hideSideNav');
}
}
}

function checkCookie() {
var cookieName = getCookie("State");
var getStatus = (localStorage.getItem('State')) ? localStorage.getItem('State') : getCookie('State');
if (cookieName != null) {
showElement(getStatus);
}
}
window.onload = function() {
checkCookie();
}
var doc = document;
var openBtn = doc.getElementById('btn-open');
var closeBtn = doc.getElementById('btn-close');

closeBtn.addEventListener('click', function() {
document.body.classList.add('hideSideNav');
closeBtn.style.display = "none";
openBtn.style.display = "inline-block";
setCookie("State", "btn-open");
localStorage.setItem('State', 'btn-open');
});

openBtn.addEventListener('click', function() {
document.body.classList.remove('hideSideNav');
openBtn.style.display = "none";
closeBtn.style.display = "inline-block";
deleteCookie('State');
localStorage.removeItem('State');
});

Answer №1

After the body tag is loaded, I quickly insert this script tag.

By this time, the browser has probably already begun creating the DOM/CSSOM, and rendering the content.

Consider moving the script to the HEAD section, and applying the class to the HTML element (document.documentElement) instead of BODY.

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

Utilize one ajax response for three distinct sections/divisions

After making an ajax call, I am receiving a total of 27 results that I need to divide equally into three sections, with 9 results in each. The sections are displayed below: HTML: <div id="content"> <section> </section> <s ...

Content not aligned in the center of the page on Internet Explorer

Recently, I've taken on the responsibility of managing the content for this website after it was passed down from the previous developer. Each page's content is contained within a div element with the class "ct", which has auto margins applied t ...

Implementing a custom body class in AngularJS when utilizing partials

Looking for some help with AngularJS. I have an index.html file, along with controllers and partials. The <body> tag is located in the index.html. I am trying to set the class for the body using my controller. After adding a value to $scope.body_c ...

Looping the Connection between Socket.io and Node

I have encountered a problem with my Unity client connecting to my node server using socket.io. While the initial connection is successful and acknowledged, when I try to emit a message to the connected client, the connection seems to get reopened as if a ...

Error during Webpack Compilation: Module 'jQuery' not found in Travis CI with Mocha Test

I've been struggling to automate tests for my repository using mocha-webpack and Travis CI. The local machine runs the tests smoothly, but Travis CI hasn't been able to complete them yet due to an unresolved error: WEBPACK Failed to compile wit ...

Automatically remove the entered data

Let's say I have a text input field with the initial value of "insert text here" coded like this: <input type="text" value="insert text here" /> What I want is for the text inside the input field to disappear automatically when the user clicks ...

Alignment issue detected

I was attempting to center these 4 divs inside a container both horizontally and vertically, but they are stuck at the top edge of the <div>. They aren't moving down and remain fixed at the top. /* Footer */ #footer { width: 100%; hei ...

Utilizing Angular Filters to Assign Values to an Object within a Controller

I have a JSON example with multiple records, assuming that each name is unique. I am looking to filter out an object by name in the controller to avoid constant iteration through all the records using ng-repeat in my HTML. { "records": [ { "Name" : ...

How come the nth-child selector remains unaffected by other selectors?

Here is an example that I have created for this issue: http://jsfiddle.net/SXEty/ <style> table td, th { padding: 8px; text-align: left; } table td:nth-child(1) { color: red; } table td { color: blue } </style> ... <table> <tr> ...

What is the process for enabling multiple consumers to subscribe to a shared topic in RabbitMQ and receive identical messages?

Although there is a similar question with an answer here, I remain uncertain whether the limitation lies in RabbitMQ's capabilities or if I simply need to conduct further research. Coming from a JS/Node background where the event pub/sub pattern func ...

Refresh the page when the dropdown selection is changed and send the new value

I'm currently working on a page that includes a dropdown menu. My goal is to have the page reload after selecting an option from the dropdown so that it returns to the same page with the selected value passed through. Here's the PHP code for th ...

Error: React Native Component Exception - a potential hiccup in

As a newcomer to React Native, I've encountered an issue while trying to bind data from a local JSON server API. Everything worked fine when I used a class component for my EventList, but after integrating Navigation in App.js and changing it to a fun ...

the live binding feature fails to function properly once an append operation is executed

Could someone please explain to me why adding an even number of squares causes the bind event to stop working? $("#add").click(function(){ $("#container").append("<div class=\"square\">xxxxxx</div> ").bind("click",function(e) { ...

What options do I have for personalizing this Google Bar Graph?

I am currently working on creating a Google bar chart. You can view my progress here: http://jsfiddle.net/nGvdB/ Although I have carefully reviewed the Google Bar Chart documentation available here, I am struggling to customize the chart to my needs. Spec ...

What are some cookie serialization techniques in JavaScript and PHP?

I have a form with multiple select options that I want to save in a cookie for user convenience. The goal is to make the serialization of the cookie easily readable in both JavaScript and PHP, allowing me to set the form onLoad and filter search results ba ...

What is the best way to extract the last JSON object from a JSONArray based on a specified value

I am currently working with a JSONArray that looks like the following: [ { "id": 1, "firstName": "abc", "isActive": true }, { "id": 2, "firstName": "cde", "isActive": false }, { " ...

What is the best method to verify the presence of jQuery on a webpage using Python/Selenium WebDriver?

Our in-house automated testing framework is built using Selenium Webdriver in Python, with a mapping system linking object names to identifiers on webpages. However, we are encountering issues due to not waiting long enough for AJAX calls to complete, caus ...

The Node function will yield a BluebirdJS Promise

I've encountered a minor issue with this script. While it functions properly, the "runTenant" method is not returning a promise that needs to be resolved with "all()". Here's the code snippet in question: Promise.resolve(runTenant(latest)).then ...

What steps can I take to ensure that the full tingle modal, which includes an image, is visible when the

Upon loading the page, I noticed that if the browser width is greater than 540px, the modal displaying an image gets cut off (see figure below). What steps should I take to ensure that the vertical scroll bar appears immediately? https://i.sstatic.net/cJv ...

How can you use ng-click to disable a div in AngularJS?

I'm looking to dynamically disable a div in AngularJS based on a certain condition. I know I can achieve this by adjusting the CSS (such as reducing contrast and color) but the div also has an ng-click property that I want to prevent from being trigge ...