Hiding the container element with "Display: none" disrupts the jQuery calculation of absolute positioning for child elements

HTML:

<a href="" id="show_link">Show</a><div id="container">
<form class="form">
    <a href="" class="align_middle">Link1</a>
</form>
<form class="form">
    <a href="" class="align_middle">Link2</a>
</form>
<form class="form">
    <a href="" class="align_middle">Link3</a>
</form>

Javascript:

var align_elements = function(item) {

    var paddingValue = 20;

    $(item).css("position", "static");
    $(item).css("float", "left");
    $(item).css("width", "auto");

    var elementWidth = $(item).width();
    var parentElementWidth = $(item).parent().width();

    elementWidth = Math.min(elementWidth, parentElementWidth - paddingValue*2);
    $(item).css("width", elementWidth);

    var elementHeight = $(item).height();
    var parentElementHeight = $(item).parent().height();
    var topPosition = (parentElementHeight - elementHeight)/2;
    var leftPosition = (parentElementWidth - elementWidth)/2;

    $(item).css("position", "absolute");
    $(item).css("left", leftPosition + "px");
    $(item).css("top", topPosition + "px");

    $(item).css("float", "");
};

$(document).ready(function(){

    var allElements = $(".align_middle");

    $.each(allElements, function(index,value){
            align_elements(value);
    });

    $(allElements).bind("DOMNodeInserted",function(){
            align_elements(this);
    });


    $("#show_link").click(function(event){
            event.preventDefault();
            $("div#container").toggle();
    });

});

CSS:

.form {
    position: relative;
    border-color: brown;
    border-width: 3px;
    border-style: dotted;
    width: 150px;
    height: 150px;
    float:left;
    margin-left: 10px;
    overflow: hidden;
}
div#container{
    overflow: auto;
    margin-top: 10px;
}

I intend to conceal the div#container using display: none; CSS property so that it's not visible on page load, yet this disrupts the functionality of the align_elements feature.

However, when I use a $.get callback function to hide the elements, everything works as expected. (The toggle link also functions properly.)

What is causing this behavior?

Fiddle: http://jsfiddle.net/7PELA/3/

Answer №1

When it comes to the CSS display:none; property, it completely removes the element from the browser's processing, which can cause issues with jQuery calculations. It is recommended to use the Visibility property in CSS and set it to hidden instead.

Here is the updated HTML:

<a href="" id="show_link">Show</a>
<div id="container" class="hide">
    <form class="form">
        <a href="" class="align_middle">Link1</a>
    </form>
    <form class="form">
        <a href="" class="align_middle">Link2</a>
    </form>
    <form class="form">
        <a href="" class="align_middle">Link3</a>
    </form>
</div>

Updated CSS:

.form
{
position:relative;
border-color:brown;
border-width:3px;
border-style:dotted;
width: 150px;
height: 150px;
float:left;
margin-left:10px;
overflow:hidden;
}

div#container
{
overflow:auto;
margin-top:10px;
}

.hide {
    visibility:hidden;
}

Updated jQuery:

var align_middle = function(element){

    var sidePadding = 20;

    $(element).css("position", "static");
    $(element).css("float", "left");
    $(element).css("width", "auto");

    var width = $(element).width();
    var parentWidth = $(element).parent().width();

    width = Math.min(width, parentWidth - sidePadding*2);
    $(element).css("width", width);

    var height = $(element).height();
    var parentHeight = $(element).parent().height();
    var top = (parentHeight - height)/2;
    var left = (parentWidth - width)/2;

    $(element).css("position", "absolute");
    $(element).css("left", left + "px");
    $(element).css("top", top + "px");

    $(element).css("float", "");

};

$(document).ready(function(){

    var elements = $(".align_middle");

    $.each(elements, function(key,value){

        align_middle(value);

    });

    $(elements).bind("DOMNodeInserted",function(){
        align_middle(this);
    });


    $("#show_link").click(function(event){
        event.preventDefault();
        $("div#container").toggleClass('hide');
    });

});

Answer №2

What do you think of trying this link: http://jsfiddle.net/5R3TF/9/

All it needs is a quick addition of

$("#show_link").trigger('click');
right after the "toggle click" function without having to specify 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

The Eclipse software is unable to detect the external CSS files

Whenever I apply external CSS to my screen, the JSP page seems to be unaware of the Bootstrap CSS. https://i.sstatic.net/DYGKQ.png https://i.sstatic.net/QUYnI.png ...

Bootstrap dropdown menu fails to open when clicked

Need assistance! I have the Bootstrap 5 navbar and dropdown menu set up, but when I try to open the dropdown, nothing happens <!-- NAV BAR BOOTSRAP 5--> <nav class="navbar navbar-expand-lg bg-light"> <div class="container-fluid"> ...

Creating a new element with a specified ID attribute in JavaScript

I have written a piece of code that performs the following actions. It creates a paragraph element and then appends it to a div in the HTML. I would like to give this newly created paragraph element a unique identifier (ID) and set the name of the ID so th ...

Press the Enter key to submit

Encountering issues while trying to enter an event. Despite reviewing several posts on this matter, a solution has not been found yet. The project needs to function properly in Chrome, FF & IE (8,9,10,11), but it is currently not working on any browser. T ...

Using jQuery sortable to update a hidden field with image IDs following a sorting activity

Below is the HTML code snippet that I am working with: <section class="layers-multi-image-container layers-has-multi-image"> <ul class="layers-multi-image-list multi-image-list layers-sortable ui-sortable"> <!-- Image --> <li> ...

Ways to include a date within a JSON object in an HTML element

Inside a meta tag attribute, I have JSON: <head> <title>PLD Interaction pattern</title> <meta data-pageObject='{ "page": { "pageInfo": { "pageID": "12345", "pageName": "smartphones:samsun ...

Is it achievable for a modal popup to automatically move to a specified location?

I need assistance with... Is it feasible to display an external webpage within a modal window and have that page automatically scroll to a specific section (such as an anchor point)? ...

Enhancing Next.js with custom CSS for React-Bootstrap components: A step-by-step guide

After installing the react-bootstrap module using the pm command and importing it into my _app.js file, I encountered an issue when trying to modify the Bootstrap code for my navbar component. The code snippet provided below showcases the navbar component: ...

Struggling to display the default value on a <select> element using the defaultValue prop in React

My objective is to create a dropdown menu that lists all the US state names. If there is a stateName in this.props (obtained from the redux store with values like NY, KY, or an empty string), I want the dropdown to display it by default. Otherwise, I want ...

Creating an HTML table using an array of objects

I'm currently working on creating a function that will generate an HTML table from an array of objects. The array provided below is what I need to convert into a table. let units = [ { 'code': 'COMP2110', &apos ...

pick out particular values from an array

I have a question that may seem basic to some, but I'm curious about how to select specific elements from an array. In this case, I have an array with 100 elements: var cubes = [element1, element2, element3 ...] and I want to select elements 25-35. ...

Leveraging jQuery to tally total inputs contained within a div

My current structure looks something like this: <div id="container"> <div class="field_shell"> <label for="name">Name</label> <input type="text" name="name" id="name" class="field"> </div> & ...

Is there a way to update the content of both spans within a button component that is styled using styled-components in React?

I am interested in creating a unique button component using HTML code like the following: <button class="button_57" role="button"> <span class="text">Button</span> <span>Alternate text</span> ...

Challenge with Responsive Design

I'm struggling with implementing a responsive design for the first time. When I check the site on my iPhone, everything appears to be zoomed in for some reason. My goal is to have the logo aligned to the left within the '.container' when v ...

Creating a series of tiny vertical markings along the horizontal line using the input range

I have a range input and I am looking to add small vertical lines at intervals of 10 on the horizontal line representing each default step. The range of my input is from 0 to 40 and I would like to have small vertical lines at 10, 20, and 30. I need to ac ...

AJAX calls are interrupted due to recursion

On a webpage, I am displaying log files that users can select and delete. The deletion process is carried out through an AJAX request where the ID of each log to be deleted is passed as parameters. However, I have encountered a problem when dealing with a ...

Unable to prepend '1' to the list

My goal is to display a list as '1 2 3...', but instead it is showing '0 1 2...' var totalLessons = $('.lesson-nav .mod.unit.less li').length; for (var i = 0; i < totalLessons; i++) { $('.lesson-nav .mod.unit.les ...

The occurrence of Multiple Button events leads to an error message stating: "Uncaught TypeError: Cannot read property 'remove' of undefined"

I am struggling to add an EventListener to each Delete Button (1,2,3) as I keep encountering an error that says "add" is undefined. Do you have any suggestions on how to fix this issue? My goal is to display a confirmation window when the DELETE button is ...

Execute a script using an HTML button

I have a HTML button element with the following code: <a class="btn btn-sm btn-danger"><i class="ace-icon fa fa-reply"></i>Reset CM</a> Also, I have an Angular variable called "{{product.name}}". My goal is to execute the follow ...

The navigation bar and footer are not utilizing the entire width of the browser

Something seems off on the Safari browser, as there's still a gap in the right side of the navbar and footer. I've been using Bootstrap and steering clear of Javascript. Any ideas on how to fix this? Appreciate any help. Thanks! Here's the ...