What is the best way to preserve the allocated space in the DOM while utilizing CSS display:none?

I have explored the functionalities of display:none and visibility:hidden. However, I need to utilize display:none for a specific reason while still preserving the element's allocated space in the DOM to prevent any impact on adjacent elements. Is this achievable?

This question follows up on the issue identified with the display:none property. You can refer to the original question HERE

UPDATE: As per T.J. Crowder's request, all relevant details from my initial query are provided here.

How can I incorporate a smooth fade effect into my function for more seamless animation instead of toggling visibility hidden / visible at regular intervals?

I am not interested in using plugins or adding the jQuery UI library.

My JS :

setBlinkingInterval: function(elem, event) {
    if (intervalIdForBlinking != 0) 
        window.clearInterval(intervalIdForBlinking);

    $(elem).show();
    intervalIdForBlinking = setInterval(function() {
       if (eventsObj.eventIsFinished(event)) {
          timer.setClosedStatus(elem, event);
       }
       else {
          if (elem.css('visibility') == 'hidden') 
             elem.css('visibility', 'visible');
         else 
             elem.css('visibility', 'hidden');
       }
   }, 500);
} 

Update 1: HTML markup included for better understanding of one answer.

$('<span/>')
            .append('<div id="closing_blink" class="yellowText" style="display:none;">' + closing + '&nbsp;</div>')
            .append(date.formatFullDate(new Date(event.timeUtc)) + timezone)
            .append('<br/>')
            .append((weatherInfo != '' && trackInfo != '') ? '<div class="whiteText">' + weather + '</div>' + '<div class="orangeText">' + weatherInfo + '</div>' + '&nbsp;' + '<div class="whiteText">' + track + '</div>' + '<div class="orangeText">' + trackInfo + '</div>' : '')
            .appendTo(rightTd);

Upon implementing solutions based on the given answers, I encountered display issues when viewed on the page.

Case 1: Using the original solution (works fine)

Screen recording link HERE

Case 2: Utilizing the fade in/out method (Display issue)

Screen recording link HERE

Case 3: Employing the toggle method (Display issue)

Screen recording link HERE

Is there a quick fix available to resolve the display issue?

Here is the complete HTML generated by a JS function drawRaceHead: function(event) {

// Setting all race numbers back to default values
styling.makeAllRaceNumbersUnselected();

// Making the current race number active (including Racing Specials)
styling.makeCurrentEventNumberSelected(event)

// Race information
$("#raceInfo").html('');
$("#raceInfo").append($('<table/>').append($('<tr/>')))
var leftTd = $('<td style="width: 295px"/>')
        .appendTo($('#raceInfo')),
    rightTd = $('<td/>')
        .appendTo($('#raceInfo'));
// If not under Racing Specials category
if (event.parentCategoryId != 2863) leftTd.html(raceFullName + '&nbsp;' + event.name)
else leftTd.html(event.name);

$('<div id="closing_time" style="display:none"/>')
    .appendTo(leftTd)

// Date, time, weather, track
var weatherInfo = '', trackInfo = '';
if (event.markets.length > 0) {
    weatherInfo = (event.markets[0].weather == null) ? '-' : event.markets[0].weather;
    trackInfo = (event.markets[0].track == null) ? '-' : event.markets[0].track;
}

var isMSIE = /*@cc_on!@*/false;
var ieVersion = (function(reg) { return isMSIE && navigator.userAgent.match(reg) ? RegExp.$1 * 1 : null; })(/MSIE\s([0-9]+[\.0-9]*)/);

if (isMSIE && ieVersion < 11) {
    timezone = '';
}
else {
    var regExp = /\(([^)]+)\)/, timezone = (regExp.exec(new Date)[1]).split(' ')[0];
    timezone = ' (' + timezone + ')';
}

$('<span/>')
    .append('<div id="closing_blink" class="yellowText" style="display:none;">' + closing + '&nbsp;</div>')
    .append(date.formatFullDate(new Date(event.timeUtc)) + timezone)
    .append('<br/>')
    .append((weatherInfo != '' && trackInfo != '') ? '<div class="whiteText">' + weather + '</div>' + '<div class="orangeText">' + weatherInfo + '</div>' + '&nbsp;' + '<div class="whiteText">' + track + '</div>' + '<div class="orangeText">' + trackInfo + '</div>' : '')
    .appendTo(rightTd);

},

Answer №1

Please note: This answer includes various sections derived from the original post updates.


When hiding elements in your code, consider using visibility: hidden instead of display: none. By doing this, the element remains hidden but still occupies space within the layout.

To see the distinction, compare the jsbins here with this link, showcasing the use of display: none and visibility: hidden respectively.

Both examples utilize the following HTML structure:

<div>This is above</div>
<div id="toggleme">This is the toggleable element</div>
<div>This is below</div>

The first snippet employs:

(function() {
  "use strict";
  var toggleme = document.getElementById("toggleme");
  setInterval(function() {
    if (toggleme.style.visibility === "hidden") {
      toggleme.style.visibility = "";
    } else {
      toggleme.style.visibility = "hidden";
    }
  }, 400);
});

whereas the second uses:

(function() {
  "use strict";
  var toggleme = document.getElementById("toggleme");
  setInterval(function() {
    if (toggleme.style.display === "none") {
      toggleme.style.display = "block";
    } else {
      toggleme.style.display = "none";
    }
  }, 400);
});

In a comment, you mentioned using fadeOut to hide an element. This sets display: none when completed. To achieve a similar effect as visibility: hidden, consider using fadeTo which animates the opacity down to 0: View Example

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset=utf-8 />
<title>fadeTo</title>
</head>
<body>
<div>This is above</div>
<div id="hideme">This is the toggleable element</div>
<div>This is below</div>
  <script>
    $("#hideme").fadeTo("slow", 0);
  </script>
</body>
</html>

Alternatively, you can use the "complete" callback on fadeOut to adjust both display and visibility: View Live Demo

$("#hideme").fadeOut(function() {
  $(this).css({
    display: "",
    visibility: "hidden"
  });
});

If you are looking to integrate these techniques into your own code, consider simplifying it by adapting the following snippet: Live Sample

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset=utf-8 />
<title>Faded Blinking Effect</title>
</head>
<body>
<div>This is above</div>
<div id="toggleme">This is the toggleable element</div>
<div>This is below</div>
<input type="button" id="btnStartStop" value="Start">
  <script>
    (function() {
      var obj = {
        startBlinking: function($elem) {
          if ($elem.data("blinking")) {
            return;
          }
          $elem.data("blinking", true);
          fadeToZero();

          function fadeToZero() {
            if ($elem.data("blinking")) {
              $elem.fadeTo("slow", 0, fadeToFull);
            }
          }
          function fadeToFull() {
            if ($elem.data("blinking")) {
              $elem.fadeTo("slow", 1, fadeToZero);
            }
          }
        },
        stopBlinking: function($elem) {
          $elem.data("blinking", false);
        }
      };

      $("#btnStartStop").click(function() {
        if (this.value === "Start") {
          obj.startBlinking($("#toggleme"));
          this.value = "Stop";
        } else {
          obj.stopBlinking($("#toggleme"));
          this.value = "Start";
        }
      })
    })();
  </script>
</body>
</html>

Answer №2

To achieve the desired outcome, implement the following CSS:

.hidemeplease {
    display:none;
}

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

Implementing the useEffect hook in React to iterate over JSON data and update the state

Having trouble implementing job location filtering ("remote"/"in-person"/"hybrid") for my personal project. As a beginner in programming, I've spent quite some time troubleshooting the fetchLocationData function and passing URLSearchParams. I anticipa ...

What is the best way to send props from a child component to its parent in a React

I'm a beginner in React and I'm attempting to develop a "CV-Generator" similar to the one shown here. In this application, whenever a user inputs data in any of the input fields, it is automatically displayed in the render preview on the right si ...

Utilizing Immutable.js within React's Pure Components

Having some difficulty incorporating React PureComponents with Immutable.js. Take a look at this demonstration: https://codepen.io/SandoCalrissian/pen/QaEmeX The demo showcases 2 components being rendered. The first (NoramlPure) is a regular PureComponen ...

The "smiley" character added to the information during an Ajax call

Encountering an unusual issue. A colon (:) character is being appended to the JSON data sent to the server via AJAX request. https://example.com/image1.png The colon character seems to appear after sending the JSON, but it does not show up when inspectin ...

Choosing an item in an AngularJS select directive from an external origin

I'm currently working on developing a form using Angular JS for editing venue details such as address and city. The backend system is powered by Django and offers a REST API (Django Rest Framework) which I am interfacing with through Restangular serv ...

Is there a way to give only the left corners of a button a rounded look?

Here is the visual representation of the button: https://i.stack.imgur.com/Bjlkp.png ...

Is there a way to design a form that appears as though it's levitating above a div element?

I am new to web development and currently practicing by converting PSD designs into HTML pages. I am facing an issue where I need to create a form that appears to be floating on top of a div, with the form being taller than the div itself. Here is an illu ...

Node.js readline: SyntaxError: Unexpected token =>

Currently, I am diving into node.js and have found myself in need of utilizing the readline module for a new project. Below is the code snippet that I extracted directly from the official readline module example. const readline = require('readline&ap ...

Problem Installing Express Sharp using Docker

When deploying via Docker, I encountered an error with sharp, even though it works fine on my workspace. I followed all the steps but still faced issues. Error: 'linux-x64' binaries cannot be used on the 'linuxmusl-x64' platform. P ...

Different methods for organizing an array of strings based on eslint/prettier

I possess an assortment of keys that I desire to sort in alphabetical order whenever I execute eslint --fix/prettier. My inference is that such a feature does not exist by default due to its potential impact on the code's behavior. Therefore, my quer ...

Searching in real-time with ajax in CodeIgniter framework is a seamless and efficient process

I'm a beginner in CodeIgniter and eager to learn. Currently, I'm facing an issue where the data is not being populated on the search page. In the model: function fetch_data($query) { $this->db->select('*'); $this-> ...

The parent is relatively positioned and its child is absolutely positioned and floated to the left

I'm currently working on a design where I have a group of parent containers with the float left property applied. Inside each parent container, there is a child div with position absolute defined within them. Here's an example: <div class="wr ...

What is the best way to incorporate a Django variable as the width parameter in a style tag within HTML?

I'm attempting to utilize a Django variable as the percentage width value within a style tag in HTML, but it's not functioning correctly. Strangely, I've discovered that using curly braces {} within style tags is prohibited—this contradict ...

jQuery AJAX issue: No headers or response displaying in console

I am currently working on updating a web application. The live version of the app can be accessed at . We are implementing changes within the district, and I am in the process of modifying the app to accommodate these updates. My work involves three diffe ...

Modifying the disabled attribute of an input tag upon button click in Angular 2

I am currently working on a function in Angular 2 where I want to toggle the disabled attribute of an input tag upon button click. Right now, I can disable it once but I am looking to make it switch back and forth dynamically. Below is the HTML template c ...

Does the layout.tsx file in Next JS only affect the home page, or does it impact all other pages as well?

UPDATE After some troubleshooting, I've come to realize that the issue with my solution in Next JS 13 lies in the structure of the app. Instead of using _app.tsx or _document.tsx, the recommended approach is to utilize the default layout.tsx. Althou ...

Comparing two inherited classes in Typescript: A step-by-step guide

Let's say we have two classes: Animal and Dog. The Dog class is a subclass of the Animal class. I am trying to determine the types of these objects. How can I accomplish this task? class Animal {} class Dog extends Animal {} //The object can be of ...

Retrieving information within a Vue component

I am struggling to access some data I have bound to a component without success. How can I achieve this? Below is my component: export default { name: 'component-vallingby', data() { return { } }, created() {}, methods: {} } And h ...

Is there a way to utilize a cookie in order for the website to recognize that I have already agreed to the terms?

It's common for websites to ask for cookie and privacy acceptance upon loading, especially in the EU. I'm looking for a way to automatically accept these cookies so I don't have to constantly click "accept all" every time I open Chrome. My ...

Mouse hovering over the JS slider activates the sliding functionality, while removing the cursor

Hi there, I'm encountering some issues with the JS clients slider on my website. I need to pause it when the mouse is over and resume when the mouse leaves. I've double-checked the code but for some reason it's still not functioning properl ...