Active positioning within a parent div

I'm having difficulty getting a color picker JavaScript widget to function properly within a webpage that contains unchangeable elements. Some of these elements are causing the color picker to be displayed far below the link once clicked. Here is a simplified example.

The desired behavior is for "div1" to move directly below "link 1" when it is clicked. However, in reality, "div1" appears well below "link 1". If the position: relative; styling is removed from the CSS definition for divMain, then "div1" is correctly positioned.

Is there a way to position "div1" directly beneath "link 1" without removing the position: relative; styling?

function setPos(aname, dname) {
  var o = document.getElementById(aname);
  var ol = o.offsetLeft;
  while ((o = o.offsetParent) != null) {
    ol += o.offsetLeft;
  }
  o = document.getElementById(aname);
  var ot = o.offsetTop + 25;
  while ((o = o.offsetParent) != null) {
    ot += o.offsetTop;
  }
  document.getElementById(dname).style.left = ol + "px";
  document.getElementById(dname).style.top = ot + "px";
}
h1 {
  height: 50px;
}

#divMain {
  position: relative;
}
<h1></h1>
<div id="divMain">
  <a href="#" onClick="setPos('link1','div1');return false;" name="link1" id="link1">link 1</a>
  <div id="div1" style="position:absolute;border-style:solid;left:200px;top:200px;">div 1</div>
</div>

Answer №1

The div's position is determined relative to the innermost container with its position set. In this scenario, it is shifted 200px to the right and down from divMain. If divMain does not have a position set, then the positioning will be relative to the body.

If you wish to place it directly below the link, ensure both link1 and div1 are enclosed within an element with a defined position. Modify the code as follows:

<div id="divMain">
    <div style="position:relative;">
        <a href="#" onClick="setPos('link1','div1');return false;" name="link1" id="link1">link 1</a>
        <div id="div1" style="position:absolute;border-style:solid;left:0px;top:16px;">div 1</div>
    </div>
</div>

(Note that I have adjusted it by shifting it 16px downwards to position it below the link.)

As a result, div1 is now positioned at 0px, 16px relative to the newly added div, rather than divMain.

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

Utilizing the Bootstrap alert function without any arguments

https://getbootstrap.com/docs/4.0/components/alerts/ Exploring the world of Bootstrap 4.0, I came across an interesting method in the documentation: $('.alert').alert() This method allows an alert to listen for click events on its descendan ...

Trouble with firing the click event using document.createElement('a') in Firefox

I wrote a function that fetches arraybuffer data from my API, generates a temporary anchor element on the webpage, and then triggers a click event to download the file. Interestingly, this function performs as expected in Chrome. @action async loadVouc ...

What are some strategies for optimizing speed and efficiency when utilizing jQuery hover?

While developing a web application, I have created a grid using multiple div elements that are X by Y in size, determined by user input. My goal is to change the background color of surrounding divs within a certain distance when hovering over one particul ...

What is the best way to automatically insert data into a database at regular intervals, while ensuring that users are unable to manipulate the timing through inspect

Is there a secure way to insert 1 point into the database every x seconds without allowing users to manipulate the interval time through inspect element? var time = 1; var interval = setInterval(function() { if (time != time + 1) { ...

Having trouble parsing an array from req.body using Node.js Express

I am currently facing an issue while trying to retrieve an array from a JSON request using Postman. In my Node.js application, I am able to read all values from req.body except for the array. When attempting to access the array, I only receive the first va ...

"Ensuring Proper Validation for Forms with JavaScript: A Step-by-Step Guide

Here is a sample Javascript form: <form id="loginForm" name="loginForm" action="/create_session/" method="post">{% csrf_token %} <table border="0" cellpadding="0" cellspacing="0" id="id-form"> <tr> <th valign=" ...

Optimizing the Gridsome/Vue.js core bundle size: Tips and tricks

Preparing to launch a static Gridsome website, the entire site currently weighs in at 518KB (including self-hosted, heavily subsetted fonts, and minified inline SVGs) before gzipping. While not excessive in size, there's still room for improvement. A ...

What is the process for incorporating icons and choices into the header bar?

Seeking advice on how to incorporate an icon into the right side alignment of a simple blank header on my webpage, similar to the image provided. I have searched through numerous threads on StackOverflow without finding a suitable solution. Could someone s ...

Ways to create a horizontal navigation menu using jQuery UI

Hey there, I'm really enjoying all the jQuery UI features! I have a question about the navigation menu - for some reason, I can't seem to get it to display horizontally. I've been playing around with the CSS but I must be missing something ...

Tips for connecting a DOM element when a link is clicked

I am currently browsing http://localhost:8000/index.html My goal is to navigate to localhost:8006/someAddress and interact with an element with the id '157579' as well as click on a button with the id '1787' that will trigger a change ...

What is the reason for the inability to input a null byte in a file when using ascii mode with node.js?

Below is the code snippet I have written: var fs = require('fs'); var fp = fs.openSync('binary.txt', "w"); var byte = '\0'; fs.writeSync(fp, byte, null, 'ascii'); However, upon execution, when I check the con ...

Chrome debug function named "Backbone" triggered

Backbone provides the capability to activate functions in other classes by utilizing Backbone.Events effectively. a.js MyApp.vent.on("some:trigger", function(){ // ... }); b.js function test(){ doSomething(); MyApp.vent.trigger("some:trig ...

What is the best way to refresh or manually trigger the marker cluster icon update in Google Maps API?

Recently, I implemented a custom cluster HTML marker, where I attempted to dynamically change the color of my markers within the cluster. Despite debugging the code and confirming that the color variable was being updated correctly, the marker colors thems ...

Generate PDF Files Using Ajax

Currently, I am utilizing FPDF to generate my report. $pdf = new Report('P','mm','A4', $_POST); $pdf->AddPage(); $pdf->Output('file.pdf','I'); Furthermore, I am employing ajax to send a request to t ...

Exploring React's Capabilities with DOM Manipulation Libraries

When working with React and the OpenSheetMusikDisplay library, I have a situation where I dynamically add elements below a target in the DOM. The target element is a div that I reference using a ref, and everything works smoothly. However, I also need to a ...

Trouble with sending semicolons in Node.js MSSQL/MSNodesqlv8 database queries

Trying to create a simple API for interacting with a MSSQL v12 database using Nodejs. Successfully connected to the database with the mssql/msnodesqlv8 package, but encountering issues with parameterized queries. code: 'EREQUEST', number: 102 ...

Is it possible to resume CSS animation when the page is first loaded?

I'm looking for a way to ensure that my CSS animations on the elements in my header.php file continue smoothly when navigating to different pages. For example, if I have a 200-second looped animation and navigate to the "about us" page 80 seconds int ...

Having trouble retrieving the value from a JavaScript Array - the elements seem to be organized in an unconventional manner

After running a console.log, I found my array structured like this: [ { Country: 'US', CityName: 'Seattle', Region: 'WA', PostalCode: '99301', StreetName: '3512 Alaska Street' }, t ...

How to Use Jquery to Delete a Specific String

I've been attempting to remove certain strings from a string using Jquery, however it seems like the code isn't working and my variable remains unchanged. var classes = $("body").attr('class'); alert('.side-nav' + classes); c ...

Enhancing WordPress Icons for Parent and Child Elements

I am seeking to customize icons on a WordPress website. The site contains a variety of product categories, including subcategories. https://i.sstatic.net/sTm1O.png My goal is to display one icon for parent categories and a different icon for child catego ...