display the div centered at the bottom of the td that has been selected

My table includes various input fields that need to be handled in a certain way.

When the user hits the enter key while using an input field, I want to display a div right below the selected input (centered).

For demonstration purposes:

You can view my implementation on jsfiddle:

http://jsfiddle.net/alonshmiel/Ht6Ym/2371/

This is how the HTML code looks like:

<table>
    <tr>
        <td><input type="text"></input></td>
        <td><input type="text"></input></td>
        <td>fshsfh</td>
        <td>347</td>
        <td><input type="text"></input></td>
    </tr>
</table>

<div id = "myDiv" class="callout bottom" style="position:absolute;display:none;">sgsf f shfs hfs hfsh </div>

Answer №1

Here is the link you asked for: http://jsfiddle.net/kRHLH/3/

The alignment is not perfect yet, but I am currently working on adjusting it. Despite that, I believe it looks good. The red box starts at the beginning of each input field, and my goal is to center it properly by calculating the width of the input element and performing additional calculations.

This code snippet contains only the JavaScript section. For the full implementation including slight modifications to the CSS, please refer to the provided fiddle link.

$('input').live('keypress', function (event) {
    if (event.which == '13') {
        d = document.getElementById('myDiv');
        d.style.display = "";
        elOffsetX = $(this).offset().left;
        elOffsetY = $(this).offset().top;
        d.style.left = elOffsetX+'px';
        d.style.top = elOffsetY+'px';
    }
});

Answer №2

If you want to center an element based on another element, follow these steps:

  1. Begin by getting the width and left values of the element you wish to center on
  2. Next, determine the width of the element you want to center
  3. Calculate half of both widths
  4. Deduct the half-width of the element you are centering on from the half-width of the element you are centering
  5. Add this new value to the left position of the element you are centering on

Here's an example in code:

$('input').on("keypress",function(e){
    if(e.which=="13"){
      //Fetches the bounding rectangle of the element providing dimensions like left,top,right,bottom,width,height
      var rect = this.getBoundingClientRect();
      var l = rect.left;
      var b = rect.bottom;
      var iw = rect.width;
      var dw = $("#myDiv").outerWidth();
      $("#myDiv").css("left",(l+((iw/2)-(dw/2)))+"px");
      $("#myDiv").css("top",b+"px");
      $("#myDiv").show();
    }
});

Check out this JSFiddle Demo for a visual representation.

Answer №3

Check out the code on JSFiddle

$("#myDiv").css("left",$(this).offset().left);

Insert this snippet of code right after you remove the display:none property from the div.

Keep in mind that this code won't precisely center the div to the input, but rather align it to the left. If you wish to center it, you'll have to calculate the widths of both elements (the div and the input) and adjust the code accordingly.

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

What is the best way to eliminate the left margin entirely in CSS?

I am attempting to create an image view that fully covers the window, without any margins. I have tried various solutions such as setting the body margin and padding to 0, but they do not seem to work. body { margin: 0px; padding: 0px; } or *, html { ...

Exploring Vue.prototype attributes and utilizing them

I'm facing a challenge while attempting to globally set a property using Vue.prototype. This is what I currently have: microsoftTeams.initialize(); microsoftTeams.getContext((context) => { Vue.prototype.$teamsContext = true; }); new Vue({ ...

Utilizing a dropdown list from one HTML page on a separate HTML page

My web project includes a main html5 page called main.html and two additional html5 pages named country.html and state.html. The country.html page contains a select dropdown list with 250 countries listed as options. <select> <option value="1 ...

Having trouble with React throwing a SyntaxError for an unexpected token?

Error message: Syntax error: D:/file/repo/webpage/react_demo/src/App.js: Unexpected token (34:5) 32 | 33 | return ( > 34 <> | ^ 35 <div className="status">{status}</div> 36 <div className=&quo ...

Using ng-show in an AngularJS directive template to animate a div

I've developed a custom message directive that displays success and failure messages based on values assigned to the directive scope. Markup <custom-message msg='message' type='messagetype'></custom-message> Directiv ...

When hovering over, make sure not to conceal the item

When I hover over the blue table, two red buttons named del-row-td and del-column-td appear. However, they disappear when I move my mouse away from the table. https://i.sstatic.net/WiWRU.png I want to prevent these red buttons from disappearing when I ho ...

Troubleshooting Problem: Difficulty accessing Controller in AngularJS Module

I am facing difficulties with communication between my application and a module that I have developed. Below is the AngularJS module that I created. (function (document, window) { 'use strict'; var piCart = angular.module('piCart& ...

The sidebar on the right side of the screen is content to relax beneath my

The positioning of my sidebar is currently below the content on the left side of the page, but I want it to sit beside the content on the right side. I've tried various solutions from similar questions without success. Here is an example of how I woul ...

What steps can be taken to ensure that JSON.parse() interprets all numbers as BigInt values?

I'm dealing with numbers in JSON that exceed the limits of the Number type, so I'd like to convert them to bigint. How can I do this? {"foo":[[0],[64],[89],[97]],"bar":[[2323866757078990912,144636906343245838,44169598393274215 ...

Refrain JavaScript - sift through an array of objects based on the values of a primitive array in linear time

I've got an array of objects that looks like this: [{ itemType: 'bottle', itemId: '111' }, { itemType: 'bottle', itemId: '222' }, { itemType: 'bottle', ...

relocate HTML components

I've been trying to reposition HTML elements within the body of a webpage, but I'm struggling with getting a form tag to appear exactly in the center of the browser - and only that form tag. Can anyone offer guidance or suggest relevant topics fo ...

Using JavaScript in PHP files to create a box shadow effect while scrolling may not produce the desired result

Issue at hand : My JavaScript is not functioning properly in my .php files CSS not applying while scrolling *CSS Files are named "var.css" #kepala { padding: 10px; top: 0px; left: 0px; right: 0px; position: fixed; background - c ...

Select a file and upload an image promptly after it is chosen

Is there a way to automatically upload an image once a user selects a file in their browser? Similar to how it works on Facebook, where users can choose a file for their cover or profile image and then the upload process begins. Currently, all I have is ...

"Experience the power of Vue.js 3 and vue-router as the @click event seamlessly refreshes the entire

Just getting started with Vue and I'm trying to figure out how to toggle the menu open/close on mobile navigation without causing the whole page to reload. Any suggestions on how to prevent that? Here's my code: <router-link to="/ " @click="t ...

Sophisticated CSS design featuring a heart-shaped cutout from the background

I am trying to design a shape using only CSS (no images) that is the opposite of a heart shape. It's a bit hard to explain, so here is a visual representation: The blue represents the background, but the shape I am aiming for is not a heart, it is ac ...

Queries about CSS3 Animations

I am attempting to make three elements appear sequentially on the page, but I'm encountering an issue. When I implement my code, all three elements show up at once, with the first element seemingly skipping its animation entirely. Then, the second ele ...

updating the background image in CSS after uploading a photo using Ajax

Whenever I click on an element, it triggers an input dialog that allows me to upload a photo. The server then responds with a JSON OBJECT containing 4 items: NAME, TYPE, HEIGHT, WIDTH. My goal is to refresh the element's background with the newly upl ...

Tips for saving a cookie received from an Express server in React using the fetch API

My current project involves creating a signup form using React, Express, and MongoDB. I have successfully managed to save user data in the database through a post request. However, although the user information is being saved in the database, I am facing ...

What is the method for toggling background URLs?

Currently, I am utilizing flaunt.js by Todd Moto for my navigation system. My goal is to seamlessly switch the hamburger image with another image when the mobile-menu is shown and hidden. Check out the demo here. For a detailed tutorial, visit this link. ...

An issue with rendering in IE8 when using richFaces and JSF with an empty text node

I'm working with a form that looks like this: <rich:dataList var="var" value="#{bean}" styleClass="styleClass"><h:form> <h:commandLink value="#{var.prop}" action="#{bean.action}"> <a4j:actionparam name="var" value="#{var.i ...