Strategies for avoiding sudden movements in the navigation bar?

I've encountered a small issue while working on my personal project and I'm seeking some guidance. The technologies I'm using include Bootstrap4, ejs templating engine, and express. In my project, the Navbar display differs based on whether the user is signed in or not - showing Sign in when they're not signed in and Account when they are.

Below is a snippet of the relevant part of the Navbar:

<div class="collapse navbar-collapse" id="navbarSupportedContent">
  <ul class="navbar-nav ml-auto ">
    <li class="nav-item  navbar-item">
      <a class="nav-link" href="/">Home </a>
    </li>
    <li class="nav-item navbar-item">
      <a class="nav-link" href="/">Some link </a>
    </li>
    <li class="nav-item navbar-item " id="nav-signIn">
      <a class="nav-link" href="/signIn">Sign in</a>
    </li>
    <li class="nav-item dropdown  navbar-item" id="nav-account">
      <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown"
        aria-haspopup="true" aria-expanded="false">
        Account
      </a>
      <div class="dropdown-menu" aria-labelledby="navbarDropdown">
        <a class="dropdown-item" href="#">Action</a>
        <a class="dropdown-item" href="#">Another action</a>
        <div class="dropdown-divider"></div>
        <a class="dropdown-item" href="#">Something else here</a>
      </div>
    </li>
  </ul>
</div>

This JavaScript function controls the display logic on the client side:

function displayAccountOrSignIn() {
    if (!document.cookie.split(';').filter((item) => item.includes('logedIn=')).length) {
      document.querySelector('#nav-account').style.display = 'none'
    }
    else {
      document.querySelector('#nav-signIn').style.display = 'none'
    }
}

The issue I'm facing is that the Navbar appears to be 'jerking' as it loads the HTML first and then hides the elements that should not be displayed. One possible solution would be to check cookies on the server-side and conditionally render parts of the Navbar, but I'm not sure if this is the best approach. Any suggestions would be greatly appreciated.

Answer №1

There are several options to consider in this situation. Identifying the best recommendation would likely involve experimenting with your actual website and testing out various approaches. All methods will effectively prevent the display of unwanted content, but some may load faster than others.

  1. Initially hide all conditional content (to prevent anything from being displayed prematurely) and then use conditional Javascript to selectively reveal specific parts as needed.

  2. By default, keep the entire toolbar hidden in the HTML code until after executing the conditional logic. Then, only display the toolbar once its status has been finalized at the end of the Javascript process. To avoid causing layout shifts, consider using visibility: hidden instead of display: none.

  3. Embed your conditional script directly within an inline <script> tag right after the toolbar HTML. This approach ensures that the script runs immediately after the toolbar HTML is rendered. You can combine this technique with either #1 or #2 above.

  4. Determine the appropriate toolbar state on the server-side so that the HTML sent to the browser is already correctly configured. Since the server possesses information about whether a user is logged in, this method should be feasible.

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

What is the best way to transfer a variable from a bash CGI script to an index HTML page?

My homepage is located at ./index.html, and I want to show a variable that was generated in my ./cgi-bin/print_ip.sh script on this page. What is the most efficient method to achieve this task? ...

Encountered an unexpected comma token while attempting to map an array in ReactJS

Can't figure out why I'm getting an error when trying to map an array in React with the following code: const { loading, error, posts } = this.props; return( {posts.map(onePost => ({ <p key={onePost.id}>{onePost.title}&l ...

Utilizing Google Maps API to automatically set an address on page load

As a beginner in using the Google Maps API, I have successfully integrated a Google Map into my project. However, I am struggling to figure out how to set specific addresses on the map. I have a list of 2,000 entries in a database, each including an addres ...

The connection to the database has been successfully established

I am a beginner with Node.js, Express, etc. I want to fetch information from the database when a client enters the contact page and then display the contact page in JSON format. Below is my code snippet: app.get('/contact', function(req, res){ ...

Can const variables be reassigned in JavaScript programming?

Can you reassign a const variable in JavaScript? In C++, we can cast variables to and from const. Is there something similar in JavaScript? My question is const a = 1; unconst(a); a = "xyz"; a === "xyz" // true I'm not referring to object prope ...

Click to save image using jQuery

I am trying to implement a feature where clicking on an image allows users to download it. I am using the download attribute for this purpose. <a href="http://mysite.ru/userfiles/certificate_2.png" class="download-certificate-link" data-title="certific ...

Issue with AngularJS directive template not rendering on the webpage

I have created an AngularJs directive that is supposed to display a div in the template. However, when I run the code, nothing appears on the screen. Below is the HTML code: <div ng-app="SuperHero"> <SuperMan></SuperMan> </div> ...

How to display a button conditionally in a React component

One element on my website is a component that handles the pagination of blog posts. Clicking the "load more" button loads an additional five posts to the bottom of the page each time. However, I'm currently stuck on solving an issue related to this fu ...

Creating a straightforward image slideshow using jQuery featuring next and previous buttons

I am looking for assistance in adding next and previous buttons to this slider. I came across a code snippet on a blog that could be useful, which can be found at .net/dk5sy93d/ ...

What is the best way to manage the delay that occurs when using the append() function?

I'm using jQuery to append an array to a div and I want to display a loading indicator while this process is happening. I added a callback function to my append logic, which works fine. However, the loader disappears before the array is fully rendered ...

Error: When attempting to send a message in a different channel, an undefined property 'send' is encountered causing a TypeError

I'm utterly stumped as to why I keep encountering this issue, so perhaps someone here can shed some light on it. The error message reads: TypeError: Cannot read property 'send' of undefined Here is the snippet of code in question: client.o ...

Having a slight hiccup with pixel alignment and browser compatibility in my jQuery animation

To emphasize a specific paragraph element, I developed a JavaScript function that displays it above a darkened background. My approach involved using jQuery to generate an overlay and then duplicating the targeted paragraph element while positioning it ab ...

Checking whether a node stream operates in objectMode

When working with a node js stream object, how can I ascertain if it is an object stream in objectMode? For example, suppose I have a readable stream instance: const myReadableStream = new ReadableStreamImplementation({ options: { objectMode : true } ...

Having difficulty manually concealing the launch image on the physical device

When testing my trigger.io app on the Android simulator or my Nexus phone, I can manually hide the launch image through code successfully. However, when running the app on the iOS simulator, the launch image remains visible. Additionally, when debugging di ...

Can AR.js be used to implement extended tracking in Augmented Reality on the web?

Currently, I am working on a web-based project using THREE.js and AR.js for augmented reality. One issue I have encountered is that when the "marker" moves out of view of my camera, the augmented reality image either disappears or remains stuck on the edg ...

Achieve top-notch performance with an integrated iFrame feature in Angular

I am trying to find a method to determine if my iframe is causing a bottleneck and switch to a different source if necessary. Is it possible to achieve this using the Performance API? This is what I currently have in my (Angular) Frontend: <app-player ...

Tips for transferring information from controller JavaScript to view JavaScript within AngularJS

Currently, I am working on an angularJS application where I retrieve data from a REST service within the controller. The retrieved data is then passed to the view using $scope. However, I encountered an issue when trying to use this data in my in-page Java ...

Port number for PM2 in an Express application

ecosystem.config.js module.exports = { /** * Application configuration section * http://pm2.keymetrics.io/docs/usage/application-declaration/ */ apps : [ // First application { name : 'cms_stage', script ...

How can JavaScript be used to identify duplicate elements within an array?

In a recent interview, I was tasked with finding repetitive elements in an array. While I was able to do so using a for loop, the interviewer requested a more efficient method without using a for loop. I am relatively new to exploring Java script and would ...

File sharing that prevents users from downloading the document

Looking for a way to securely share a PDF file between 2 individuals without allowing the second user to download it? Here's the scenario: 1. User has a document that needs to be shared with user2. 2. User 1 selects the file to share from their comp ...