What is the proper way to place a newly added element using absolute positioning?

Currently, I am in the process of developing a tooltip feature. This function involves adding a div with tooltip text inside it to the element that is clicked. However, I am facing a challenge in positioning this element above the clicked element every time. How can I achieve this?

$(document).ready(function() {
  $('.tooltipTarget').click(function() {
    var title = $(this).data('tooltip');
    if (!$('p.tooltip').hasClass('active')) {
      $('<p class="tooltip active"></p>')
        .text(title)
        .appendTo($(this));

      $('.tooltip').addClass('test');
      $(document).on('click', function(e) {
        if (e.target != $('.tooltipTarget')[0]) {
          $('.tooltipTarget').trigger('click');
        }
      });
    } else {
      $(document).off('click');
      $('p.tooltip.active').fadeOut(250, function() {
        $(this).remove();
      });
    }
  });
});
.tooltip {
  margin-top: -45px;
  opacity: 1;
  transition: 0.3s ease-in-out;
  position: absolute;
  border-radius: 1px;
  color: #767676;
  box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2);
  background: #f7f7f7;
  padding: 10px;
  font-size: 12px;
  text-align: left;
  z-index: 10;
  max-width: 250px;
  &.active {
    opacity: 1;
  }
}
.tooltip::before {
  content: '';
  display: inline-block;
  height: 0;
  width: 0;
  position: absolute;
  z-index: 10;
  bottom: -14px;
  right: 50%;
  right: calc(50% - 7px);
  border-left: solid 7px transparent;
  border-right: solid 7px transparent;
  border-bottom: solid 7px transparent;
  border-top: solid 7px #f7f7f7;
}
.tooltip::after {
  content: '';
  display: inline-block;
  height: 0;
  width: 0;
  position: absolute;
  z-index: 9;
  bottom: -15px;
  right: 50%;
  right: calc(50% - 7px);
  border-left: solid 7px transparent;
  border-right: solid 7px transparent;
  border-bottom: solid 7px transparent;
  border-top: solid 7px rgba(0, 0, 0, 0.2);
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <title>CSS3 tooltip</title>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
  <script type="text/javascript" src="script.js"></script>
  <link rel="stylesheet" type="text/css" href="style.css">



</head>

<body>

  <button style="margin: 200px;" data-tooltip="This is a tooltipThis is a ltipThis is a tooltipThis is a tooltipThis is a tooltipThis is a tooltipThis is a tooltipThis is a tooltipThis is a tooltipThis is a tootooltipThis is a tooltipThis is a tooltipThis is a tooltipThis is a tooltipThis is a tooltipThis is a tooltipThis is a tooltipThis is his is a tooltipThis is a tooltipThis is a tooltipThis is a tooltipThis is his is a tooltipThis is a tooltipThis is a tooltipThis is a tooltipThis is his is a tooltipThis is a tooltipThis is a tooltipThistooltipThis is a tooltip"
  class="tooltipTarget">orempaks[djo[psad</button>

</body>

</html>

P.S. I prefer not to rely on the basic HTML title functionality.

Answer №1

Here is a solution that should be useful...

.tooltipTarget {
position: relative;
}

.active-tooltip {
position: absolute; 
bottom: 100%; 
left: 50%; 
width: 400px;
transform: translateX(-50%);
}

Answer №2

If you want to specify the exact location of your click event in relation to a specific container element, you can do so by following these steps...

To determine the offset of the clicked element, as well as the PageX and PageY of the mouse click event, you can then calculate where your tooltip should appear:

  $('#container').click(function(e) {
    var offset = $(this).offset();
    var top = e.pageY - offset.top;
    var left = e.pageX - offset.left;

    alert('OFFSET: ' + top + ', ' + left);
  });

By using these calculations, you can set the position of your tooltip with values for top and left.

Check out this example

For adding an element to the container at the click position, see this demonstration: Example 2 (Includes most of your CSS styles).

Answer №3

Check out this CSS code snippet:

button.tooltipTarget {
position: relative;
}
p.tooltip.active {
position: absolute; 
bottom: 100%; 
left: 50%; 
width: 400px;

transform: translateX(-50%);
}
.tooltip {
margin-top: -45px;
opacity: 1;
transition: 0.3s ease-in-out;
position: absolute;
border-radius: 1px;
color: #767676;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2);
background: #f7f7f7;
padding: 10px;
font-size: 12px;
text-align: left;
z-index: 10;
max-width: 250px;
&.active {
    opacity: 1;
}
}
.tooltip::before {
content: '';
display: inline-block;
height: 0;
width: 0;
position: absolute;
z-index: 10;
bottom: -14px;
right: 50%;
right: calc(50% - 7px);
border-left: solid 7px transparent;
border-right: solid 7px transparent;
border-bottom: solid 7px transparent;
border-top: solid 7px #f7f7f7;
}
.tooltip::after {
content: '';
display: inline-block;
height: 0;
width: 0;
position: absolute;
z-index: 9;
bottom: -15px;
right: 50%;
right: calc(50% - 7px);
border-left: solid 7px transparent;
border-right: solid 7px transparent;
border-bottom: solid 7px transparent;
border-top: solid 7px rgba(0, 0, 0, 0.2);
}

View the DEMO here

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

Tips for making a dropdown menu within an Ionic Side menu

Looking for guidance on creating a sub menu in the ionic framework? I'm new to AngularJS and ionic framework, but eager to learn. Below is the code snippet I used to create a dropdown list component: <ion-side-menu side="left"> <ion-co ...

Exploring the possibility of detecting page scrolling in Javascript by clicking on scroll bars

I have implemented a unique feature on my page that allows users to scroll up and down using custom buttons I created. This functionality is achieved by smoothly transitioning between anchor points on the page using jQuery's animate function. However ...

Step by step guide on uploading files using Vue.js and Express.js

Hello there, I am new to Vuejs and Express and I'm looking to practice my skills. Currently, I am attempting to build a User Profile with an image upload feature using Vuejs and ExpressJs but unfortunately, none of the files or text are uploading as ...

Fulfill the promise in AngularJS and assign it to a different factory

Presenting my factory below: .factory('UserData', ['User', '$q', function(User, $q) { var deferred = $q.defer(); return { user: null, get: function() { var _this = this; _this. ...

Effective ways to manage extensive forms in Angular 2

I have a complex form in my application. What is the most effective way to collect data from this form and transmit it to the API using Angular 5? ...

Angular is not providing the anticipated outcome

I'm new to Angular (7) and I'm encountering an issue while trying to retrieve the status code from an HTTP request. Here's the code snippet used in a service : checkIfSymbolExists() { return this.http.get(this.url, { observe: 'res ...

Tips for expanding an input field to span across two td elements

I am attempting to design a simple form. The issue I am encountering involves creating an input field that spans two td's in the second row of my table. Despite using the colspan="2" attribute within the td tag, the input field does not expand over tw ...

Modify the collapse orientation in Bootstrap

I would like the button to expand from the bottom when clicked and collapse back down, instead of behaving like a dropdown. <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_ ...

Using Backbone to Retrieve a JSON File from a Server: Deciding Whether to Include the File Extension ".json" in the URL or URLRoot

Exploring Backbone with exercise by trying to obtain a JSON file from the server using the urlRoot property of the Model. Encountered an error (404) when setting urlRoot: "./js/json/todo", paths with ".json" work but console.log(todoItem.get('descrip ...

Tips for simplifying a JavaScript function

Hello everyone, I just joined StackOverflow and I could really use some assistance with a JavaScript and jQuery issue that I'm facing. Can someone suggest a more efficient way to write the code below?: jQuery(document).ready(function () { $("#ar ...

Server has sent an Ajax response which needs to be inserted into a div

I have a modal window that sends a POST request to the server. Before returning to the view, I store some information in ViewData. Here's an example of what I'm doing: ViewData["Msg"] = "<div id=\"msgResponse\" class=\"success ...

A helpful guide on displaying validation errors in a form using React JS

After creating a form and connecting it to the server, I encountered an issue with displaying validation errors below respective input fields. The error message response in case of validation error is as follows: "message": "ValidationError: confirmPasswor ...

Typescript - type assertion does not throw an error for an invalid value

When assigning a boolean for the key, I have to use a type assertion for the variable 'day' to avoid any errors. I don't simply do const day: Day = 2 because the value I receive is a string (dynamic value), and a type assertion is necessary ...

Is there a way to update a JSON file using React?

I'm looking for a solution to update a JSON file in React. Is it possible? Below is the code snippet that executes when an HTML element is clicked. Ultimately, it invokes VoteTracking, the function responsible for updating the JSON file. handleC ...

Discover the process of attaching an event to the keyboard display within a Cordova application

I've exhausted my efforts trying to figure out how to assign an event for when the virtual keyboard appears on my hybrid cordova app. I'm looking to trigger a specific action whenever the keyboard shows up in my app consistently. ...

Achieving proper layout in Material-UI Autocomplete by splitting long words

Exploring the Material-UI autocomplete feature for the first time has brought some challenges my way. I am working with usernames, which have a specific length limit but could exceed the space available in the autocomplete view. https://i.sstatic.net/O8t1 ...

JavaScript that Implements MVC Architecture Using C#

When working on a cshtml page within my View, I am able to easily retrieve the URL to an action using this line of code: <h1>@Url.Action("NewComment", "Case")</h1> If I include the same code in JavaScript like this: <script> alert( ...

Issue with CSS background color not extending to full screen in webkit browsers when using 960.gs grid system

When using 960.gs, I have created a login screen with a div for the login form that has a background image. This div is positioned below a header, which centers it in the browser window. In my CSS, I am setting the body color as follows: body { backgr ...

Looking to implement a dual-column layout for posts on WordPress using Bootstrap

Creating an intranet website for a client which functions similar to a Facebook or Twitter feed. The layout includes three columns using Bootstrap's grid system. The first column serves as a navigation sidebar, while the other two columns should disp ...

What is the best way to merge variable name in AngularJS?

How to combine variable name in HTML code: app.controller example $scope.name ='abc'; $scope.abc123 = response.data; HTML example <h1>{{name}}</h1> <h1>{{{{name}}123}}</h1> <!-- I want the value of abc ...