Ways to determine the position of elements when they are centered using `margin:auto`

Is there a more efficient way to determine the position of an element that is centered using CSS margin:auto? Take a look at this fiddle:

https://jsfiddle.net/vaxobasilidze/jhyfgusn/1/

If you click on the element with the red border, it should alert you about its position relative to the parent table. The top positioning seems accurate, but the left is showing as 1 which is incorrect. One possible solution could involve calculating the position mathematically by considering the parent's width and the width of the red-bordered element. However, are there better alternatives or more efficient methods to achieve this?

$('body').on('click', '.placeHolder', function(){
alert($(this).position().left+', '+$(this).position().top);
})
.channels {
  /*border-collapse: collapse;*/
  border-spacing: 0;
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  font-weight: bold;
  border: 1px solid rgba(30, 30, 30, 1);
  border-radius: 4px;
  overflow: hidden;
  background: url(images/comment-bg3.png) repeat;
  resize: both;
}

.channels td {
  border-left: 1px solid rgba(30, 30, 30, 1);
}

.channels td:first-child {
  border-left: none;
}

.channelHeader {
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/css-element-queries/0.4.0/ResizeSensor.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/css-element-queries/0.4.0/ElementQueries.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<table class="channels ui-draggable ui-resizable" style="width: 476px; height: 266px; position: relative;" oncontextmenu="return false;" id="mainDiv">
  <tbody>
    <tr class="channelHeader ui-draggable-handle">
      <td colspan="5" class="channelName" id="channel1" audiopid="[0x33]" audiostream1="format:mp2,type:audio,pid:[0x33],width:0,height:0" interface="192.168.222.15" method="info" multicast="239.10.20.101" port="6000" protocol="udp" resolution="1920x1080" serviceid="1" servicename="undefined" serviceprovider="provider" videopid="[0x31]" videostream="format:h264,type:video,pid:[...]
...

Answer №1

To determine the distance between the .placeHolder div and the .vid td elements in relation to the document, you can utilize the .offset() method:

$('body').on('click', '.placeHolder', function(){
    var vidOffsetLeft = $('.vid').offset().left;
    alert(($(this).offset().left - vidOffsetLeft) + ', ' + $(this).position().top);
});

Answer №2

If you're working with JavaScript, I recommend trying this approach: First, assign an id (for example 'redbox') to the element with the red border. Then, use the following code snippet:

var targetElement = document.getElementById('redbox');
    var style = window.getComputedStyle(targetElement);
    var marginValue = style.getPropertyValue('margin');

This code allows you to retrieve the CSS margin value of the specified element. Good luck using this method - hope it proves helpful! :)

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

Every time I invoke a module, non-global variables are utilized

Within a module.exports file, I am facing an issue where the variables are shared among different instances of the module. Instead, I want each call to the module to have its own set of values for cycle number, original data, new product, etc., similar to ...

Is there an Angular directive that can replicate a mouseenter event?

Is there a way to simulate a mouseenter event with a directive? I have been searching for a directive that can simulate a mouseenter event, but all I have found so far is one that binds a function to mouse over or karma tests for simulating mouse over. W ...

Iterate through a large JavaScript object using setTimeout

What is the most efficient way to iterate through large object elements without freezing the browser? I have successfully looped through arrays using setTimeout/setInterval in this manner: var i = 0; var l = arr.length; var interval = window.setInterval( ...

The searchbar is failing to load the requested information through AJAX

I'm encountering an issue that I just can't seem to pinpoint. The goal is for the page to initially load all data, and upon hitting search, only display the requested data without refreshing the page. (Ideally, I would like to be able to modify ...

A basic problem involving appending content using jQuery

I have encountered a puzzling issue. Whenever I attempt to insert new content into the <div> element using my JS code, it briefly appears and then disappears abruptly. I am unsure of the reason behind this behavior. Is there a way to prevent this fr ...

Struggling to implement Datatables row grouping using ajax is proving to be quite challenging

Is there a way to group rows in a table based on date ranges, using the data from the first column ("Due_Date"), and leveraging the rowGroup extension provided by Datatables? I've tried various solutions found online, such as using the data property ( ...

problem with saving session data

I am attempting to access data from another page using session storage. On my initial page, named home.html function go_to_faq(qnum){ window.open('FAQ.html', '_blank'); sessionStorage.setItem('key2', qnum); } <a s ...

Effortlessly find data in an HTML table and showcase the results instantly without

I am looking for a way to implement search functionality in my table without refreshing the page. The fields above the table are used for searching and I want the results to be displayed within the same table. Here is an example of the code: <?php $for ...

Controlling ever-changing routes using AngularJS

My AngularJS app (Angular v1) has a secure login system in place. Users who are not authenticated can only access the login page, forgotten password page, and cookie policy. I am utilizing ngRoute as shown below: $routeProvider .when('/login ...

increase the number of rows in the table automatically

I've encountered an issue while working on a form that involves getting a value from a jQuery spinner and dynamically adding that number of rows to a table inside the form. Despite using firebug to debug, I couldn't pinpoint the exact cause of th ...

Using a personalized font in your RShiny application

I'm interested in integrating a unique custom font into my Rshiny App. I have a feeling that the necessary code should be placed within tags$style, but I am unsure of the exact syntax needed for this integration. Below is an example code snippet: ui ...

I'm having trouble grasping the issue: TypeError: Unable to access the 'subscribe' property of an undefined object

I've been working on a feature that involves fetching data from API calls. However, during testing, I encountered some errors even before setting up any actual test cases: TypeError: Cannot read property 'subscribe' of undefined at DataC ...

What is the best way to organize data subsets in Firebase?

I am currently working on saving data from multiple sections within my webapp. One section involves storing employee information, while the other deals with employer group information. However, when I save this data in Firebase, it all gets organized by ID ...

Incorporating Vuetify into a Vue CLI application with the help of webpack

I am facing an issue with my Vue CLI application that uses Webpack and Vuetify. The Vuetify components are not loading properly, and I keep getting the following warnings: Unknown custom element: < v-app > - did you register the component correctly? ...

Node-RED experiences crashes while attempting to make HTTP requests to access a web service

I'm currently facing a challenge in creating a node that can make web service calls. The tools I'm using are: Node-RED version: v0.17.5 Node.js version: v8.4.0 An exception is being thrown, and here's the error message: node-red_1 ...

Subsequent $http requests become trapped in a pending state and eventually fail with a NodeJS server

I encountered a strange issue with Angular and Node that I can't seem to find a solution for. In my Angular controller, I have a function that fetches data initially and stores it in $scope. This function also allows the controller to make a POST req ...

Creating a drop-down menu that aligns perfectly under the bar in Material-UI: What you need to know

While working with Material-UI, I encountered a problem with my drop-down menu. Every time I click on it, it covers the bar instead of appearing below it (see image links below). https://i.stack.imgur.com/1Y8CL.jpg https://i.stack.imgur.com/emf87.jpg Is ...

The nuSelectable plugin enhances the functionality of jQuery

I am currently experimenting with the jQuery nuSelectable plugin in order to enable users to select multiple items simultaneously. Unfortunately, I am encountering difficulties in making the selection work as intended. You can find the plugin here. After ...

Consolidate two AJAX requests into a single callback

I'm developing a Chrome extension and facing the challenge of merging two separate AJAX calls into one callback upon success. What would be the most efficient approach to achieve this? Auth.prototype.updateContact = function(id, contact_obj) { var ...

Exclude a particular row from a table when there is no identifier

My PHP code generates a basic table. <table border="1" id="control> <tbody> <tr>...</tr> <tr>...</tr> <tr>...</tr> //Row #3 <tr>...</tr> <tr>... ...