Place a div element on top of the others by using the onClick() event to "dock" it

Can someone help me with setting/docking a div element above another div? The div contains some other divs and form objects, serving as an inputbox dialog that should appear right above an element when clicked. I have set the onClick() event for a

Click <span onClick="showInputbox()">here</span> to set value
element.

I'm not sure if this is achievable with CSS alone, so any assistance would be greatly appreciated. Thanks in advance!

Update: My main issue lies with positioning - specifically placing one element above another (such as a label or spanned text). This isn't solely about showing or hiding the element.

In terms of the script:

function showInputbox(){
var txt = document.getElementById("txtHere").style;
var dlgInput = document.getElementById("dlgInput").style;

dlgInput.top = txt.top + dlgInput.height;
dlgInput.left = txt.left;
dlgInput.visibility = "visible";
}

However, this doesn't seem to be working as intended. The values for .top and .left always return null. What am I missing here?

Answer â„–1

If you're looking to stack two sibling divs on top of each other, you can achieve this using CSS positioning since they share the same parent.

An example for this setup can be found here. Here's what it involves:

  • The HTML consists of a straightforward structure with 2 divs sharing a common parent.
  • In the CSS, I assigned width, height, and background properties to both divs, setting the display property of the first one as none initially.
  • I also positioned the hidden div using position:absolute, which allows me to utilize attributes like bottom, left, right, and top.
  • Notice that I added position:relative to the parent element. This is crucial because position:absolute positions elements in relation to the closest parent with a position attribute set as relative or absolute.

  • Next, jQuery library was used to implement the onClick() event which toggles the visibility of the hidden div when the second div is clicked.

  • IMPORTANT: Make sure to add the onClick() event only after the DOM has fully loaded (in the provided jsFiddle, 'DomReady' option is selected, and in jQuery, you have the ready event).

Note: The jQuery part can also be accomplished using pure JavaScript, but using the library is recommended due to its efficiency and widespread use.

Update:

http://jsfiddle.net/GLf4X/5/

HTML:

<div id="parent">
    <div id="child1">
    </div>
    <div id="child2">
    </div>
    <div id="child3">
    </div>
</div>

CSS:

#child1{
    width:300px;
    height:50px;
    background:#333;
    display:none;
    position:absolute;
    bottom:100%;
}

#child2{
    width:300px;
    height:50px;
    background:#666;
    margin-bottom:100px;
}

#child3{
    width:300px;
    height:50px;
    background:#999;
}

#parent{
    margin:60px auto;
    position:relative;
}

Javascript:

function getOffset( el ) {
    var offset = { top: 0, left:0 };
    if( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
        offset.left = el.offsetLeft - el.scrollLeft;
        offset.top = el.offsetTop - el.scrollTop;
    }
    return offset;
}

function displayAboveElement(event){
    event.stopPropagation();
    var divToShow = document.getElementById('child1'),
        clickTarget = event.target;
        offset = getOffset(clickTarget);
    divToShow.style.display = 'block';
    console.log(clickTarget.style);
    divToShow.style.top = (offset.top - clickTarget.clientHeight) + 'px';
    divToShow.style.left = offset.left + 'px';
}

document.getElementById('child2').onclick = displayAboveElement;

document.getElementById('child3').onclick = displayAboveElement;

Addressing your issue:

  • The error occurred because you were attempting to retrieve left and top values from an element where they haven't been defined yet, resulting in null values.
  • left and top are specifically applicable to elements styled with position:absolute.
  • An element's style reflects inline style attributes only, not what we intend here.

As demonstrated, coding vanilla JavaScript involves several challenges (cross-browser compatibility, etc.), hence utilizing a library like jQuery is highly recommended.

My Solution:

  • Determined the relative offset top and left of the clicked element concerning its immediate parent.
  • Applied these values as inline styles to the designated div for display purposes.

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

Determine whether the server request originated from an Ionic mobile application

Currently, we are in the final stages of completing an Ionic project with a PHP backend. To enhance the security of our backend and protect it from external influences, we aim to restrict access to the backend only from within the Ionic project (native app ...

Tips for comparing props in the ComponentDidUpdate method when dealing with a complex data structure that is connected to Redux

I have been experimenting with the new lifecycles of React v16. It works perfectly fine when comparing single keys. However, when dealing with large data structures like Arrays of objects, performing deep comparison can be quite expensive. My specific sce ...

When I click on "Submit", it redirects me to the PHP page

I've followed a tutorial on creating custom PHP contact forms at this link: and made some modifications to the form for my specific requirements. However, when I click the Submit button on the form, it redirects me to the PHP page. What I actually w ...

Deliver asynchronous requests using Web Components (Model-View-Controller)

I am currently working on developing an application using pure javascript and Web Components. My goal is to incorporate the MVC Pattern, but I have encountered a challenge with asynchronous calls from the model. Specifically, I am creating a meal-list com ...

Enable Vue2 Select Component to accept a variety of arrays for selection choices

I am currently developing a customizable Select component that can be used with any Array provided as options. It is working well when the object properties in the array have the same names bound in the component. However, if an array of objects with diff ...

Seeking assistance with a peculiar JSON parsing challenge

When making an ajax call and receiving what seems to be well-formed json, I encounter strange issues with parsing. Interestingly, it works fine on my development server but fails when the code is live online. The data retrieved from the ajax call looks li ...

Conceal elements and offspring in D3.js through the utilization of JavaScript or jQuery

I am currently customizing a fantastic force directed layout created by @eyaler (http://bl.ocks.org/eyaler/1058611) that offers multiple options. My goal is to conceal a specific node with its children using jQuery or D3 along with JavaScript, not directly ...

Is there a specific point in which we can directly pass a value to the `state` in Redux?

Is it safe to directly pass the value to the state in a redux reducer like this? export default (state = [], action) => { switch (action.type) { case 'FETCH_USER': return [...state, action.payload]; default: return state; ...

Adjusting dimensions using CSS

I am facing an issue where my tab names are displaying too large and I would like them to be default size. I have placed the following script in the <head>. <style type="text/css"> { font-family: Verdana; font-size:40%; } ...

JavaScript functions are experiencing issues when used within the document.ready() function

I am facing an issue where adding a second function in JavaScript causes it to stop working on my page. Could someone help me identify the possible error? Your assistance would be greatly appreciated. It's worth noting that when I comment out the sec ...

Error: Unable to modify the div content - Uncaught TypeError: Unable to assign value to innerHTML of null

Attempting to update the contents of a div using JavaScript and innerHTML, but encountering an issue. After implementing the code to change the div's content, the functionality stopped working. The syntax has been double-checked. Tools being used in ...

Tips on sending information to a different page through jQuery's AJAX functionality

I'm facing an issue with an ajax call. Below is my code for the ajax: $('#Subjects').click(function() { $.ajax({ type: 'POST', url: '../portal/curriculum.php', data: 'studentNumber=&apos ...

utilize the flex index.html layout

Upon reviewing the template, I noticed that there is code implemented to check if the client has the necessary version. This code performs certain actions based on whether or not the required version is available. Additionally, there seems to be an <obj ...

Is there a combination of 'auto' and 'none' values in any CSS properties?

Is it safe to assume that if a property is set to auto, it cannot have the value of none, and vice versa? Or if a property has none, can it not have auto as well? I understand that these values have distinct meanings, but I am curious if this concept has ...

Creating an automated CRUD API using Node.js, Express, and Mongoose

In the realm of Python, we have often relied on tools like tastypie or Django-Rest-framework to build Rest APIs. After delving into Felix Geisendörfer's article Convincing the boss, one particular statement caught my attention: Node.js truly exce ...

I'm caught in a never-ending cycle as I navigate through sending information to my Python API and subsequently utilizing that information in the Next.js application to execute the Python script

I am encountering an issue with the response message, getting "Error sending data." The problem seems to arise when trying to retrieve data in server.py that is already specified in the code. For example, instead of using "msg_user", I should use ...

Troubleshooting Angular 4's ng-selected functionality

I'm currently facing an issue with getting ng-selected to function properly. Initially, I attempted to simply add selected in the option tag, but later discovered that I should be using ng-select. Despite trying variations such as ng-selected="true" a ...

YUI3 Searching with Selectors

I'm encountering an issue with selecting a single checkbox object in YUI3 based on its unique value attribute. In a table, there are multiple checkboxes with assigned unique keys to their value attributes. What should be the correct selector in YUI3 t ...

The compression feature in express.js middleware is not functioning correctly

The middlewares set up in my app are as follows: app.use(express.favicon(__dirname + '/static/public/images/favicon.ico')); app.use(express.compress()); app.use(express.json()); app.use(express.urlencoded()); app.use(express.cookieParser('S ...

What is the best way to style radio boxes in HTML to resemble checkboxes and display X's when selected?

I'm looking to create a form with radio boxes that resemble checkboxes and display a glyphicon x when selected. I've experimented with various solutions such as: input[type="radio"] { -webkit-appearance: checkbox; /* Chrome, ...