Positioning an element in the center of another using JQuery

Greetings! I am currently working with some elements that look like this:

<div id="one">content</div>
<div id="two">content</div>

These elements are followed by another set of elements (without any parent, placed directly after the body tag) which have the following CSS property:

position: absolute;

Each of these additional elements has an ID similar to this example:

id="helper-one" refers to id="one"

My goal now is to position the second group of elements exactly in the middle (both vertically and horizontally) of the elements they refer to. How can I achieve this?

I attempted using offset:

    var one_offset = $("#one").offset();

    $("#helper-one").offset({ top: one_offset.top, right: one_offset.right, left:one_offset.left, bottom: one_offset.bottom})

However, this code only sets the position for the top and left, resulting in the helper element being positioned at the top-left corner of the target rather than its center.

Answer №1

jQuery.fn.center = function (obj) {
  var loc = obj.offset();
  this.css("top",(obj.outerHeight() - this.outerHeight()) / 2 + loc.top + 'px');
  this.css("left",(obj.outerWidth() - this.outerWidth())  / 2 + loc.left+ 'px');
  return this;
}

Usage example:

$("#helper-one").center($("#one"));

Note: You can also skip providing the obj argument by parsing the id of the original element

jQuery.fn.center = function () {
  var obj = $('#' + this.attr('id').split('-')[1]), loc = obj.offset();
  this.css("top",(obj.outerHeight() - this.outerHeight()) / 2 + loc.top + 'px');
  this.css("left",(obj.outerWidth() - this.outerWidth())  / 2 + loc.left+ 'px');
  return this;
}

$(document).ready(function(){
   $("#helper-one").center();       
});

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

A guide on effectively selecting an element with the '@font-face' tag

I'm endeavoring to design a distinctive logo by utilizing a personalized font... and am keen on incorporating it into my CSS As an illustration: the identifier for my div element is "logo" Should I merely employ this code? #logo { font-family: ...

Error code 70006 encountered in Typescript when attempting to reference a type as "any"

Currently, I am working on a React project that involves using TypeScript. This is quite new to me, and I have encountered a type error in one of my components... let dragStart = (e) => { let transferringData = e.dataTransfer.setData("text", e.tar ...

Validating an Element Directive in AngularJS: A Step-by-Step Guide

I have developed a directive for handling numbers function numberInputDirective() { return { restrict: 'E', scope: { model: '=', disabled: '=?', decimals: ...

Building a table using jQuery and adding elements using JavaScript's append method

Greetings! I've been attempting to add new records from a form that registers or updates student information, but unfortunately it doesn't seem to be functioning correctly. Can anyone point me in the right direction as to why this may be happenin ...

Enhance a DOM element using personalized functions in jQuery

Seeking advice on how to create custom widget placeholders with a "setvalue" function specific to each type of widget: $.fn.extend($(".dial"), { setval: function(val) { }); Attempting to avoid extending jQuery.fn directly since different widget type ...

Feeling puzzled about the next() function in Node.js?

https://github.com/hwz/chirp/blob/master/module-5/completed/routes/api.js function isAuthenticated (req, res, next) { // If the user is authenticated in the session, call the next() to proceed to the next request handler // Passport adds this met ...

Fade in upcoming content over prevailing content utilizing jQuery

Looking to implement a fade-in effect for new posts retrieved from my database. The existing posts are initially loaded in a div when the page loads, and I would like the new posts to smoothly appear above the old ones. Recently began exploring jQuery and ...

What is the best way to align these div elements within a table cell?

I am encountering an issue with the placement of elements. What I am striving for is something like this: https://i.stack.imgur.com/VSFXE.png where a div with several other divs inside is positioned at the top of the td, and another div is at the bottom o ...

Sending data from an AJAX request to a Spring controller is a common task in web

var TableDatatablesEditable = function () { var handleTable = function () { function restoreRow(oTable, nRow) { var aData = oTable.fnGetData(nRow); var jqTds = $('>td', nRow); for (var i = 0, ...

Utilizing v-if and splice on users to select items from v-model

After following a tutorial, I have the code snippet below that I would like to enhance: <div style="margin-top: 10px;"> v-for="task in taskItems" :key="task.id" <q-icon :name="task.icon"/> <div ...

ClickAwayListener's callback function stops executing midway

I am currently utilizing Material-UI's ClickAwayListener in conjunction with react-router for my application. The issue I have come across involves the callback function of the ClickAwayListener being interrupted midway to allow a useEffect to run, on ...

The onChange event was not able to be activated within the material-ui radioGroup component

Utilizing the RadioButton component to showcase different options of a question within a custom-built component: import FormControl from "@material-ui/core/FormControl"; import FormControlLabel from "@material-ui/core/FormControlLabel"; import Grid from " ...

What is the best way to transmit a two-dimensional array using ajax?

Here is the process I use to send data to the server: var points = []; var coords = polyline.geometry.getCoordinates(); for (var i = 0; i < coords.length; i++) { var x = (coords[i][0]).toFixed(4); var y = (coords[i][1]).toFixed(4); points[i ...

Store the response data in a global variable or forward it to another function in Node.js using Express JS

I'm currently working on a function that makes a post request to an API (app.post), sending a token and a URL for redirection to webpay. The challenge I'm facing is saving that token in a global variable so that it can be accessed by another func ...

JQuery Challenge: Solving Dynamic Modal Issues

I'm in the process of creating a webpage that features multiple divs, each with its own unique image and title. Within each div, there's a button that, when clicked, should grab the specific image and title and display them in a modal. However, I ...

Adding a background image to a box in MUI is a simple task that can enhance

I've been attempting to include a background image in the Box component of mui, but I can't seem to get it to work. Here is the code I've been using: const Main = () => { return ( <Box sx={{backgroundImage:'images/cove ...

The issue with displaying Fontawesome icons using @import in CSS-in-JS was not resolved

I recently changed how I was importing Fontawesome icons: src/App.css @import "@fortawesome/fontawesome-free/css/all.css";` After shifting the @import to CSS-in-Js using emotion: src/App.js // JS: const imports = css` @import "@fortawes ...

What could be causing the if statement to evaluate as false even though the div's style.display is set to 'block'?

Building a react application using createreactapp and encountering an issue with an if statement that checks the CSS display property of a div identified as step1: const step1 = document.getElementById("step-1") if (step1.style.display === 'blo ...

Something seems off with Chrome

I am facing a unique issue that I need help with. Unfortunately, the code is too long to post here but essentially it involves creating a menu for a website. The menu works perfectly and looks great on all browsers except for Chrome. This is unusual as Ch ...

I am looking to change the state of only the element that is being moused over in a React Hooks useState function, rather than changing the

Currently, I have a component from line 61-67 that controls the state of an editIcon. The issue is that it changes the state values for all items in the column, rather than just the specific item or row it should apply to. When hovering over a span element ...