What is the best way to add a new div below a specific div without disrupting the existing layout of other elements on the page?

Is there a way to create a new div that appears below a specific div on a webpage, but is displayed above all other elements without affecting their positioning? Here is an example:

  ---------------------------------------------
  |               |          |                |
  |    div1       |   div2   |         div3   |
  |               |          |                |
  ---------------------------------------------
  |                     |                     |
  |    div4             |         div5        |
  |                     |                     |    
  ---------------------------------------------
  |... additional divs...

I am looking to generate a new div in the onClick handler of div2, so that when div2 is clicked, a new div will be shown that is aligned to the left of div2, appears below div2, and is positioned on top of other elements below it. The layout of the page will be:

  ---------------------------------------------
  |               |          |                |
  |    div1       |   div2   |         div3   |
  |               |          |                |
  ---------------------------------------------
  |               |                  |        |
  |    div4       |     Newly        |  div5  |
  |               |     Created      |        | 
  -----------------     Div          ----------
  | ...additional |                  |        | 
  |    divs...    |                  |        | 
  |               |                  |        | 
  |               |                  |        | 
  |               |                  |        | 
  ---------------------------------------------

The solution needs to be versatile. For example, the JavaScript function might look like this:

 createDivBelow(css selector, height, width)

This function would create a div below any specified div, aligned to the left, with the specified height and width. The key challenge is ensuring that the new div is absolutely positioned to prevent the movement of other elements. I believe that the new div should be positioned absolutely, possibly with respect to the body element. However, determining the correct position is the issue, especially if div2 is nested within other elements.

EDIT in response to feedback and proposed solutions I require a solution that is independent of the page structure and does not rely on the CSS of other elements. The solution should be agnostic to the placement of div2 within the document.

Answer №1

Updated based on feedback from the original poster

One way to achieve this is as follows:

  1. Upon clicking a div, add a class to it that changes its position to something other than static, such as position: relative, set its z-index to a value higher than the other divs, making it appear on top.

  2. Attach the newly created div to the clicked one, positioning it absolutely with left: 0 and top: 100%, ensuring it aligns to the left/bottom without affecting other elements, regardless of which div is clicked.

By implementing the above method, the layout remains responsive, adjusting to screen width changes seamlessly.


Here's a simple demonstration:

Code snippet:

$("nav div").click(function () {

  $(this).toggleClass('haspopup');

  if ($(this).hasClass('haspopup')) { 
     $(this).append("<div class='popup'>Here is your popup</div>");
  } else {
     $(this).find('.popup').remove();
  }
  
});
nav {
margin-top: 50px;
  display: flex;
  counter-reset: demo;
}
nav div {
  border: 1px solid black;
  flex: 1;
  padding: 20px;
}
nav > div::before {
  content: 'DIV';
}
nav + div {
  background: lightgray;
  padding: 20px;
}

nav div.haspopup {
  position: relative;
  z-index: 1000;
}
nav div.haspopup .popup {
  position: absolute;
  left: 0;
  top: 100%;
  background: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<nav>
  <div></div>
  <div></div>
  <div></div>
</nav>

<div>This element won't move or be affected when the popup shows</div>

Answer №2

It seems like you're interested in creating a navigation bar. Here's a sample code snippet to get you started:

$("nav div").click(function () {
  if ($(this).data("menu")) {
    $(this).data("menu").remove();
    $(this).removeData("menu")
  } else {
    var t = this.offsetTop;
    var l = this.offsetLeft;
    var h = this.offsetHeight;
    $(this).data("menu",
      $("<div class=\"menu\">menu</div>")
      .appendTo(document.body)
      .css({ "left": l, "top": t + h})
    );
  }
});
body {
  position: relative;
  padding-top: 2em; /* test */
}
div {
  display: inline-block;
  border: 1px solid black;
  box-sizing: border-box;
}
nav div {
  width: 100px;
}
main div {
  width: 150px;
}
.menu {
  background: white;
  position: absolute;
  padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav><div>div 1</div><div>div 2</div><div>div 3</div></nav>
<main><div>div 4</div><div>div 5</div><main>

Answer №3

Here is a solution that may be beneficial to you:

$(document).ready(function(){
    $(".child").click(function(){        
        createDivBelow($(this), "150px", "150px");
    });
});
function createDivBelow(cssSelector,height,width){
        $(".newchild").show();
        $(".newchild").css({"left":cssSelector.position().left+"px"});
        $(".newchild").css({"top":(cssSelector.position().top+cssSelector.height())+"px"});
        $(".newchild").css({"height":height});
        $(".newchild").css({"width":width});
}
.parent{
width:100%;
}

.child{
  width:150px;
  height:150px;
  float:left;
  border:1px solid gray;
}
.newchild{
  position:absolute;
  width:150px;
  height:150px;
  display:none;
  background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  
  <div class="child">div1</div>
  <div class="child">div2</div>
  <div class="child">div3</div>
  <div class="child">div4</div>
  <div class="child">div5</div>
  <div class="child">div6</div> 
  <div class="child">div7</div>
  <div class="newchild">Newly created div</div>
</div>

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

Database entry does not appear in Internet Explorer until the browser is completely shut down and reopened

Currently, I have a form with two dropdowns. Selecting an option from the first dropdown automatically populates the second dropdown. Everything works well except for a minor issue I observed recently. When I add a new item to the second dropdown, it gets ...

Navigation guard error: Caught in an infinite redirect loop

I have set up a new vue3 router and configured different routes: const routes = [ { path: "/", name: "home", component: HomeView, }, { path: "/about", name: "about", component: () => ...

Why does the pound symbol in z-index always show up in Angular?

Having an issue with my code where I set a z-index in the CSS like this: .mat-mini-fab { position: absolute; right: 5px; top: 4px; z-index: 999; box-shadow: none !important; } However, whenever I visit my site, the z-index is not being appl ...

Implementing jQuery into cfdiv component

My current setup involves using a cfdiv to bind data from another page, like (bind.cfm?id=123). This other page (bind.cfm) contains a jQuery scrollable feature from Flowplayer found at . However, the scrolling function is not working as expected. I have al ...

When incorporating script tags in React, an "Unexpected token" error may arise

I am in the process of converting my website to a React site, but I am encountering an issue with the script tags not working. It keeps showing an unexpected token error. Here is the code snippet: <div className="people"> How many people are you ...

Guide to showcasing two spring models within a single HTML table row utilizing Thymeleaf

I need help formatting a row to display in an HTML table: "$num out of $totalCount" For example, if num=5 and totalCount=8, I want it to show as 5 out of 8. This is the code I have so far: ... <tr> <td th:text=&quo ...

The content of xmlhttp.responseText is not being displayed in the innerHTML

As part of my ongoing effort to enhance my understanding of Ajax for work purposes, I have been following the W3Schools tutorial and experimenting with my Apache2 server. In this process, I have placed a file named ajax_info.txt on the server (in /var/www ...

Utilizing the change function in conjunction with that

My attempt at creating a simple function to implement the change function didn't go as planned:/ What I am trying to achieve: 1- When a cost checkbox is checked, assign the corresponding cost (e.g., cost1.checked ? cost1 = 10 : 0) 2- Calculate and di ...

Send an object from AngularJS to an MVC controller and bind it to a corresponding class object

Trying to map an object from AngularJS to a custom C# class in an MVC controller, but encountering issues with the class object showing up as null. Here's the code snippet: $scope.Get = function () { var EService = [{ id: $scope.Id, ...

Protractor tests succeeding prior to complete page load

Recently, my protractor tests have been failing after updating the node_modules. Strangely, it seems like the tests are initiating before the page is fully loaded: Connecting to the selenium server at http://127.0.0.1:4444/wd/hub [launcher] Running 1 inst ...

Utilize Node.js to proxy Angular requests to a service hosted on Azurewebsites

I am trying to set up a proxy post request in my Node.js server and receive a response from the target of this request. Below is an excerpt from my server.js file code where I have implemented the proxy, but I am facing a issue with not receiving any respo ...

How to eliminate all special characters from a text in Angular

Suppose I receive a string containing special characters that needs to be transformed using filter/pipe, with the additional requirement of capitalizing the first letter of each word. For instance, transforming "@!₪ test stri&!ng₪" into "Test Stri ...

"How to automatically populate an input field with a value when the page loads in an

I need assistance with setting the input value to 1 when the page is loaded, but for some reason, it remains empty. Can someone help me troubleshoot this issue? <tr *ngFor="let item of cartItems; let i=index"> <td class="cart_pr ...

Guide on how to trigger a pop-up modal to open a new webpage by clicking on a hyperlink

I have a page called one.html that has a link on it <a href="#">Click to open second page<a/> When this link is clicked, I would like for second.html to open in a popup modal. The second page contains a basic table that I want to di ...

Accessing JSON data from the Public folder in a create-react-app

I have a JSON file called ipAddress.json with the following content: { "ipAddress": "11.111.111.111" } To access this file, I placed it in an "ipAddress" folder within the public directory. So now the path is "public/ipAddress/ipAddress.json". However, ...

How can I resolve the issue of not returning anything ondrop in my code?

Whenever I drop my div containing an image, I don't see anything. And when I try to access its ID, I get a null value. How can I extract information from a div with an image and append a row with it? For code samples or to check the codepen example, v ...

What is the method to individually determine "true" or "false" using .map() in coding

I am faced with an array of data that needs to be manipulated individually, but it should still function as a cohesive unit. Can you assist me in achieving this? function OrganizeFollow() { const [followStatus, setFollowStatus] = useState([]); co ...

Enhancing jQuery AJAX Performance with Promises and Deferred Objects for Seamless Callback Management

Consider this scenario: Checking the stock availability of a product multiple times in an ecommerce-script. Initially, I implemented it as follows: var checkStock = function(id) { $.ajax({ type: "POST", dataType:'json', url: "class ...

Picture will not be included in the SQL database

When users fill out a HTML form to register for a competition, everything successfully enters into the database except for the Photo Name and Photo. Any ideas on why this might be happening? HTML Form: <form method="post" action="addboat.php"> &l ...

Tips for effectively documenting CSS on a extensive website

Our website is quite extensive, with numerous pages. As we've added more pages, the amount of HTML and CSS has also increased. We're wondering if there's an efficient way to document all of this information. For example, how can we easily de ...