Tips for aligning an element with another element's position

Is it possible to have the new hello button displayed in exactly the same position as the previous one after clicking the Hello button?


      const rightDiv = document.querySelector('#rightDiv');
      const leftButton = document.querySelector('#leftButton');

      function myFunction() {
        rightDiv.style.display = "none";
        leftButton.style.display = "block";
      }
    

      <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
      <div class="row">

        <div class="col" style="height: 9vh; border: 1px solid black; width: 100%">
          <button id="leftButton" style="display: none"> Hello</button>
        </div>

        <div id="rightDiv" class="col" style="height: 9vh; border: 1px solid black">
          <button onclick="myFunction()"> Hello</button>
        </div>

      </div>
    

Edit: I want the new button's position to be identical to the original button so that it appears as if the button never moved.

Answer №1

When the display property is set to none, no box will be generated for the element. In addition, attributes like offsetWidth and offsetHeight will return 0 when there is no CSS layout box associated with the element[1].

9.2.4 The 'display' property[2]

A value of 'none' causes an element to be excluded from the formatting structure, meaning it won't generate any boxes or affect layout. Descendants of the element will also not generate any boxes; both the element and its content are completely removed from the formatting structure. This behavior cannot be changed by setting the display property on descendant elements.

Note that using a display value of 'none' doesn't create an invisible box; it eliminates box generation altogether. CSS does have mechanisms that allow an element to generate boxes that impact formatting without being visible themselves. For more details, refer to the visibility section.

Instead of using the display property, consider utilizing the visibility property. This will make the box generated by the element invisible while still affecting layout.

11.2 Visibility: the 'visibility' property[3]

The visibility property determines if the boxes generated by an element are rendered. Invisible boxes still impact layout (use the display property set to 'none' to prevent box generation altogether). Values can mean:

  • hidden The box is invisible (completely transparent, nothing is drawn), but it affects layout. Descendants with 'visibility: visible' would still be visible.

For grid layout in Bootstrap 4 using Flexbox, you can manage the order of flex items with the order property[4].

Grid system[4]

Bootstrap’s grid system utilizes containers, rows, and columns for content layout and alignment. It's based on flexbox and fully responsive. Here's an example and a detailed overview of how the grid works.

To achieve this effect, utilize the visibility and order properties:

const rightDiv = document.querySelector('#rightDiv');
const leftButton = document.querySelector('#leftButton');


function myFunction() {
  rightDiv.style.visibility = "hidden";
  leftButton.style.visibility = "visible";
  leftButton.parentElement.style.order = 1;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="row">

  <div class="col" style="height: 9vh; border: 1px solid black; width: 100%">
    <button id="leftButton" style="visibility: hidden"> Hello</button>

  </div>

  <div id="rightDiv" class="col" style="height: 9vh; border: 1px solid black">
    <button onclick="myFunction()"> Hello</button>
  </div>

</div>


If you wish to set the width of #leftButton to 100%, you can achieve this by using a pseudo-element and the align-items property.

const rightDiv = document.querySelector('#rightDiv');
const leftButton = document.querySelector('#leftButton');


function myFunction() {
  rightDiv.style.display = "none";
  leftButton.style.display = "block";
}
/* Position adjustment by pseudo-elements and `margin` for` padding` etc ... */

.leftColumn::before {
  flex-basis: 50%;
  content: "";
}

#leftButton {
  margin: 0 15px;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="row">

  <div class="col d-flex align-items-start leftColumn" style="height: 9vh; border: 1px solid black; width: 100%"> <!-- Use flexbox -->
    <button id="leftButton" style="display: none"> Hello</button>
  </div>

<div id="rightDiv" class="col" style="height: 9vh; border: 1px solid black">
  <button onclick="myFunction()"> Hello</button>
</div>

</div>


References:

  1. CSSOM View Module
  2. Cascading Style Sheets Level 2 Revision 2 (CSS 2.2) Specification

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

Comparing the cost of memory and performance between using classes and interfaces

As I delve into writing TypeScript for my Angular project, one burning question arises — should I use an Interface or a Class to create my domain objects? My quest is to uncover solid data regarding the actual implications of opting for the Class route. ...

What is the most efficient way to halt the pipe if the value of an HTML input element remains unchanged using RxJS?

I'm currently incorporating RxJS into my Angular 9 project. My goal is to bind a keyup event to an input field and trigger an HTTP request whenever the user types a new value. Here's the code snippet I have: fromEvent(this.inputBox.nativeElemen ...

Excessive iterations occurring in JavaScript for loop while traversing an array

After addressing the issues raised in my previous inquiry, I have made significant progress on my project and it is now functioning almost exactly as intended. The main purpose of this website is to iterate through the World Of Tanks API to generate cards ...

Search for elements once they have been dynamically loaded using AJAX with the

I have a function called getItemID which searches for all the IDs under a specific parent ID (#search-output). This function works well when the ID (#test) is already loaded when the page loads. However, I am dynamically generating these IDs (#test) using ...

Javascript's associative arrays: a versatile tool for data organization

Is there a way to achieve the same functionality in JavaScript as this PHP code?: $this->gridColumnData[] = array('field' => 'id', 'width' => 50, 'title' => 'Enquiry Id') ; $this->gridColumn ...

Failed to make a request to https://registry.npmjs.org/node-modules because of an error: error:0906D06C:PEM routines:PEM_read_bio:no start line

Encountering an issue while attempting to install a JS package. Despite conducting thorough research, I have not been able to resolve the error. Please help me identify where I am going wrong. npm ERR! request to https://registry.npmjs.org/node-modules ...

What is the best way to update the content of a particular div and its associated link ID whenever the link is clicked?

I need to update the content of a div by clicking on an href link that includes an id named data. The issue I'm facing is that I can't access the id value within my script because it's passed within a function. How can I pass the data variab ...

Loading items into multiple containers using PHP AJAX pagination

I'm looking to implement a "load more" button on my website, but I'm facing a challenge due to my three-column layout. I want to load more items into their respective parent elements without disrupting the design. While I've used infinite aj ...

Mix up and present cards for a game of blackjack (Javascript)

Have you noticed why "card2" is randomly adding an object to the array? It should consistently add objects to the array. const cards=[ { card: '&#127137', value: '1' }, { card: '&#127138', valu ...

An asynchronous function will never conclude its execution

Exploring the native async and await features in Node 7.6.0 has left me puzzled. I can't seem to figure out why my async call is just hanging instead of resolving. NLP module: const rest = require('unirest') const Redis = require('io ...

React-Tooltip trimming

Currently, I am facing a dilemma that requires some resolution. The issue at hand is related to the placement of React-Tooltip within the List element. Whenever it's positioned there, it gets clipped. On the other hand, placing it at the bottom isn&a ...

Utilizing PHP and JQuery Variables within the CodeIgniter Framework

Can someone please provide guidance on the best approach to handle this particular situation? I currently have a sidebar populated with Li Elements using a foreach loop, which is working perfectly. Each element contains a link that, when clicked, trigger ...

What are some methods for eliminating the navigation bar from eBay?

I am currently working on designing a unique product page for a modular shotgun microphone kit that can be found on eBay. However, I am facing challenges in removing the navigation bar and header bar from the page. Despite my efforts to uncheck all the bo ...

Fixed-bottom footer in Bootstrap 5 that overlays content

Having trouble creating a fixed footer using the fixed-bottom class in react & bootstrap. The issue is that it's covering some content and I've tried various solutions without success. Any suggestions on how to fix this? (Code and Demo provided b ...

In Internet Explorer 8, angular's $window service may sometimes return undefined

I've developed a custom directive called slideshow with some scope variables that are two-way bound to ng-style. This directive functions as a responsive carousel that adjusts based on the window height retrieved using the $window service. During tes ...

Tips for creating a fixed footer that adjusts with a flexible wrapper

Feeling incredibly stressed, I embarked on a quest to find the perfect sticky footer. After searching Google for what seemed like an eternity, I came across multiple tutorials recommending the use of min-height:100%. However, this approach caused the wrap ...

Tips for creating vibrant tabs or incorporating additional outputText following tabs within primefaces

https://i.sstatic.net/vtipc.png In my tabView, I have two tabs and I am trying to add a third one that looks like the attached image. I have tried using outputText for this purpose, but it doesn't seem to work as expected. Specifically, I want part o ...

How can I incorporate dynamic moving lines into my website's loading sequence?

Link to Gyazo image 1: https://gyazo.com/015425f0decb187e28b620c1e3206391 Issue with first image: https://gyazo.com/dfcd33e8a4fd5bea64e51fe40556f0bf I'm currently working on a website and came up with a cool concept of having two lines crossing the s ...

Tips for converting HTML content into a properly formatted text file

I have a user interface where users can perform various actions using ajax calls. Once the ajax call is completed, the results are displayed in a div with an id = "log". I want to provide users with an option (a button labeled Export) so that when they hav ...

Asking for access to a Node server with React authentication

Let me outline the current scenario: I am working with a database that contains registered usernames and passwords. My task at hand is to create a login form where users can input their username and password to log in. These credentials are already stored ...