Position object in the middle using jQuery and CSS

Trying to center an absolutely positioned object horizontally using CSS and jQuery is proving to be a challenge. The use of jQuery is necessary due to the varying widths of the objects. Hover over the icons in my jsFiddle to see the issue.

Check out the jsFiddle here

Currently, I have applied a left: 50% property, but I need to implement a negative margin-left that is half of the object's width. Here is the code snippet where I am facing issues:

jQuery

$('.tooltip').each(function() {
      $(this).css('margin-left', '-'+($(this).width() / 2)+'px');
}​

CSS

.toolbar .tooltip {
    position: absolute;
    left: 50%;
    margin-top: 8px;
    padding: 3px 8px;
    display: none;
}

.toolbar li:hover .tooltip {
    display: block;
}

HTML

<ul class="toolbar">
    <li><img alt="Undo" src="undo.gif" /><span class="tooltip">Undo</span></li>
    <li><img alt="Redo" src="redo.gif" /><span class="tooltip">Redo</span></li>
    <li><img alt="Help" src="help.gif" /><span class="tooltip">Help</span></li>
    <li><img alt="Feedback" src="feedback.gif" /><span class="tooltip">Feedback</span</li>
</ul>

Answer №1

Issue with unclosed code has been fixed, check out the updated code here

Just a heads up, there is padding so it's best to use "outerWidth" instead of "width". You can find the corrected code here

Answer №2

By considering the width of the block, I adjust the position of left.

$('.tooltip').each(function() {
    // Let's assume the width of the button block is 32px.
    $(this).css('left', (32 - ($(this).width())) / 2+'px');
}​);​

http://jsfiddle.net/3Cb9A/3/

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

Investigating Jquery Flip Card Issues

Looking to create a set of flip cards using HTML, CSS, and jQuery. Currently facing an issue where only the first card is flipping when clicked. Any suggestions on how to modify the jQuery code to make it work for all cards would be highly appreciated. C ...

jQuery fails to post serialized data to the action method

I'm facing an issue with submitting a form using jQuery and Ajax. My Ajax function looks like this: $('#submitForm').click(function (e) { e.preventDefault(); $.ajax({ url: '/Letter/Create', ...

Utilizing CSS for Page Orientation

For my current project, I was tasked with designing a print view using HTML & CSS. This view is then converted into a PDF on the server and sent to an A5 printer for physical output. One of the specific requirements of this assignment is that the first pa ...

Manipulate data with Jquery Serialize

There are multiple text boxes, drop down menus, and radio options on this form. Upon clicking submit, I need to save all the information entered by the user in order to store it into a database. <div id="reg2a"> First Name: <br/><input type ...

Just a Quick Query About Regular Expressions

I need help removing a specific part from a URL string, which looks like this: http://.....?page=1. I am aware that the code "document.URL.replace("?page=[0-9]", "")" does not work, so I am curious to learn how to accomplish this task correctly. Thank you ...

Manage responses from ajax submission

My settings form has a unique feature to prevent users from making changes by mistake. After completing the form, users click the save button to trigger a modal (using Bootstrap modals) asking for their password before processing the original form. If the ...

jquery is unable to fetch the input value from a dynamically generated field inside a function

Something peculiar keeps happening to me when I utilize jQuery, which is different from what others have encountered in the forums. Whenever I make an ajax call and generate an input element (on success), like so: Start Date: <input type="text" id="gr ...

Angular - when removing items from ngRepeat, the remaining elements do not transition smoothly; instead, they abruptly snap or jump into position

Currently using AngularJS v1.4.8 with ngAnimate injected into my controller. In the process of creating a dynamic list using ngRepeat, tied to an array. The addition and updating of items in the list function smoothly with animations working as intended. ...

Using Jquery Ajax to validate login information by submitting an HTML form

Working on a project involving jQuery Ajax, HTML forms, MySQL, and PHP. I have a database with registered users and I want to use a login form to retrieve user information from the database upon submission. However, I'm encountering an issue where the ...

Proper techniques for storing element count in Protractor

I am a beginner when it comes to using Protractor and I am not entirely satisfied with the code snippet below, even though it is functional. My goal is to store the count in a variable (named "nb_before") and use it later on. However, due to the promi ...

What could be causing this code to only modify one element instead of both?

One input field should be able to change two elements, however with jQuery it appears that only one element is being modified. When rearranging the order of elements in the function, such as having #inCoin first and then #receive_amount, only the #inCoin ...

[entity: undefined prototype] { type: 'clip', info: 'Watch my latest video!!' } using nodejs - multer

import routes from "./routes"; import multer from "multer"; const multerVideo = multer({ dest: "videos/" }); export const localsMiddleware = (req, res, next) => { res.locals.siteName = "Webtube"; res.locals.routes = routes; res.locals.user = { isA ...

Unleash the power of jQuery by incorporating the Ajax functionality with a hover option to enhance user interactivity. Utilize the .ajax

On my website, I have a calendar displayed with dates like "11/29/2014" stored in an attribute called "data-date". The goal is to check the server for a log file corresponding to that date and change the CSS of the div on mouse hover. Here is the current ...

Should one use Javascript library dependencies with or without bundling?

I'm in the process of packaging a library so that it can be utilized in two different ways: <script src="myLib.js"/> as well as mylib = require('myLib') However, myLib relies on several other libraries, some of which I believe the ...

The alert box is failing to open

When I click the button, I expect an alert box to appear but nothing happens. I'm unsure whether I need to include var before the identifier in the function signature like this: function popup(var message) <!DOCTYPE html> <html lang="en-ca"& ...

Transitioning into a fade out effect using CSS

I successfully created a modal using CSS and jQuery. The fade in transition works perfectly, but I'm having trouble implementing a transition for when it fades out and scales back to 1.4. The main issue is that the modal disappears too quickly. Chec ...

Incorporating a vanilla JS library (Pickr) into a NuxtJS page component

Recently, I've been experimenting with integrating the Pickr JS library (specifically from this link: [) into my NuxtJS project. To install it, I simply use NPM: npm install @simonwep/pickr In one of my NuxtJS pages - the create.vue page to be exac ...

Manipulate a property within an array using JavaScript and AngularJS

I am working with an AngularJS model that looks like this: $scope.Model = { Users : [{ UserId: '', FirstName: '', LastName: '' }], Products :[{ ProductId: '', ...

javascript download multiple PDF files on Internet Explorer

I am facing an issue with downloading multiple PDF files In my list, I have various a elements with links to different PDF files. I created a loop to go through each a element and generate an iframe using the value of the href as the source. This solutio ...

The second angular $http call fails to reach its intended destination

I am in the process of setting up a flow similar to oauth, where I delay sending an actual request until some initial negotiation has been completed. The initial negotiation is successful, however, when I attempt to make the request for the desired resour ...