Place the bottom element of the top parent element in position

Creating a simple tooltip with bottom positioning at the top of the parent element involves setting a negative height for the tooltip element. However, when checking the height of the tooltip element upon hovering, it returns 0 according to console.log().

$('.tooltip').hover(function() {
    var content = $(this).data('tip-content');
    var element= $(this).find('.tip-content');

    if(element.length == 0 ) {
        var html = $('<p class="tip-content">' + content + '</p>');
        var height= html.height();
        console.log(height);
        html.css('top', - height);
        $(this).prepend(html);
    } else {
        element.remove();
    }
});
.element {
    height: 50px;
    width: 50px;
    margin: 50px auto;
    background: #000;
}

.tooltip {
position: relative;
}

.tooltip .tip-content {
width: 180px;
margin-left: -98px;
padding: 10px 5px;
position: absolute;
left: 50%;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
background: #294a72;
font-size: 0.75em;
color: #fff;
text-align: center;
}

.tooltip .tip-content:after {
top: 100%;
left: 50%;
border: solid transparent;
content: " ";
height: 0;
width: 0;
position: absolute;
pointer-events: none;
border-top-color: #294a72;
border-width: 5px;
margin-left: -5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element tooltip" data-tip-content="This is a test content">
</div>

Answer №1

When you are checking the height, keep in mind that the element has not been added to the DOM yet. This means it won't have a height at that point. Simply rearrange your statements to ensure proper functionality. jQuery has the capability to change the CSS of an element even after it has been inserted.

var html = $('<p class="tip-content">' + content + '</p>');
$(this).prepend(html);  //Make sure this line comes before the next one
var height  = html.height();
console.log(height);

But there are still some missing details. The height() method does not account for margin or padding. To include padding, you can use outerHeight(). However, for margin, you may need to refer to the CSS or manually set a value. Additionally, since your arrow uses a pseudo-element, it cannot be accessed through DOM traversal. You might have to hardcode its dimensions.

A more comprehensive calculation for height could be:

var ARROW_HEIGHT = 5;
html.outerHeight() + parseInt(html.css('marginBottom'), 10) + ARROW_HEIGHT;

Answer №2

In order for the proper functionality to be achieved, it is necessary to add the HTML content at the beginning and proceed with determining the height and adjusting the position of the element accordingly. At present, you are only capturing the height of a variable rather than an actual HTML element.

Answer №3

Instead of getting the height of 'tip-content', you simply need to obtain the height of the 'tooltip'.

$('.tooltip').hover(function() {
    var content = $(this).data('tip-content');
    var element= $(this).find('.tip-content');

    if(element.length == 0 ) {
        var html = $('<p class="tip-content">' + content + '</p>');
        // Get height of parent element
        var height= $(this).height();
        console.log(height);
        html.css('top', - height);
        $(this).prepend(html);
    } else {
        element.remove();
    }
});
.element {
    height: 50px;
    width: 50px;
    margin: 50px auto;
    background: #000;
}

.tooltip {
position: relative;
}

.tooltip .tip-content {
width: 180px;
margin-left: -98px;
padding: 10px 5px;
position: absolute;
left: 50%;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
background: #294a72;
font-size: 0.75em;
color: #fff;
text-align: center;
}

.tooltip .tip-content:after {
top: 100%;
left: 50%;
border: solid transparent;
content: " ";
height: 0;
width: 0;
position: absolute;
pointer-events: none;
border-top-color: #294a72;
border-width: 5px;
margin-left: -5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element tooltip" data-tip-content="This is a test content">
</div>

Answer №4

To ensure that an HTML object is automatically assigned a height, you must first place it in the DOM. This is why you may initially see a height of 0. Make sure to append your object before attempting to retrieve its height.

Take a look at this example for reference: https://jsfiddle.net/9vkmzq3x/

$('.info').hover(function() {
var details = $(this).data('information');
var element = $(this).find('.details-info');

if(element.length == 0 ) {
    var html    = $('<span class="details-info">' + details + '</span>');
    var height  = html.height();
    console.log(height);
    html.css('top', - height);
    $(this).prepend(html);

    $(this).find("span").css("top",- $(this).find("span").height());
} else {
    element.remove();
}});

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

Steps to include a border around text and center align it:

As a beginner in Html and CSS, I am trying to create a heading with the text "Women safety" and wrap it with a border. However, when I apply the border to the text, it covers the entire width, extending both left and right. I only want the border to be a ...

Using v-model in Vue 3 will result in modifications to the table class in Bootstrap 5

Below is a snippet of the code I wrote: <table class="table table-striped"> <tr class="table-dark"> <th>#</th> <th>Column 1</th> <th colspan="3">Column 2</th> </tr> <tr ...

Ensuring full height on Bootstrap 4 columns without triggering a scrollbar in the browser

I'm currently working with Bootstrap 4 and attempting to make 3 columns on the page fill 100% height, only displaying scrollbars within the columns and not on the entire page. I have experimented with applying h-100 to the row div, as well as implemen ...

Update the value of input within a Struts2 iterator by utilizing JavaScript

As a junior programmer, I am trying to update the value of an input type text within a Struts2 iterator without refreshing the entire page. I believe using JSON could be a solution for this issue. Here is my JSP code: <input type="text" name="cantidad ...

What is the best way to use JavaScript to conceal a section of a form div?

After receiving some code from a certain platform and implementing it to hide part of my form div element, I noticed that the element hides and unhides quickly when running in a browser. This rapid hiding and showing behavior occurs when clicking on the bu ...

Vue.js error: Trying to access an undefined property

Here is my Vue instance setup: const vueApp = new Vue({ el: '#vue-wrapper', data: { items: [] }}); Utilizing a v-for loop in index.html.eex: <div v-for="item in items[0].subItems">{{ item.name }}</div> In this scri ...

Challenge: RxJS timeout function not functioning as expected

I am facing an issue with exiting the Observable stream after 3 seconds if there is no new string input. The problem arises when I paste the same value multiple times, as the distinctUntilChanged operator prevents the input stream from progressing. I wan ...

The website displays perfectly in Atom, however, it is not functional in any web browser

My website is currently in the development phase, and I'm experiencing issues with certain div elements not positioning correctly once the site goes live. Specifically, the "Follow Us" tab at the bottom of the site, among other divs, has been affecte ...

Incorporate new content into JavaScript using the input element

I have a unique question - can text be added to JavaScript using the input tag? For example, <input type="text" id="example" /> And let's assume the JavaScript function is: function display_text() { alert("The text entered in #example wi ...

Is there a way for me to acquire the Amazon Fire TV Series?

I'm currently working on developing a web app for Amazon Fire TV, and I require individual authorization for each app. My plan is to utilize the Amazon Fire TV serial number for this purpose. However, I am unsure how to retrieve this serial using Jav ...

Maintaining accurate type-hinting with Typescript's external modules

Before I ask my question, I want to mention that I am utilizing Intellij IDEA. In reference to this inquiry: How do you prevent naming conflicts when external typescript modules do not have a module name? Imagine I have two Rectangle classes in different ...

Is there a way to retrieve a comprehensive list of all the potential routes in my nuxt.js project?

Is there a way to retrieve a list of all the potential routes in my nuxt.js project? (this would include all URLs) ...

The alignment of Bootstrap input fields is off center

@import url( 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' ); <div class="row"> <div class="col-xs-12 text-center btn-group" data-toggle="buttons"> <label class="btn btn-primary active"> ...

Aligning text and lists using Bootstrap on both desktop and mobile devices

I want to format a text with a list similar to the images provided https://i.stack.imgur.com/6giDH.png for desktop and tablet view, but for mobile display I would like it to look like this https://i.stack.imgur.com/7zSXi.png This is my current approach ...

JSON nested error: Cannot read property 'length' of undefined

Having some trouble working with a nested array within a JSON in D3JS, specifically encountering a "property length undefined" error at the line: .attr("d", function(d) { return line(d.points); }). Below is the JSON data structure: [ { "aspectRatio" ...

Content and visual side by side

My logo and header image are giving me trouble. Whenever I attempt to center the header image, it keeps moving to the next row. How can I make sure it stays on the same row? Check out our website Thank you ...

Encountering an error in Jest with TypeScript (Backend - Node/Express) that reads "Cannot use import statement outside a module

Currently, I am in the process of developing Jest tests for a Node/Express TypeScript backend. Recently, I came across the concept of global test setup which I am integrating to streamline the usage of variables and function calls that are repeated in all ...

Is there a way to repurpose a JavaScript object that gets sent back to the client upon page loading?

Upon initial page load, an AJAX request fetches a list of JavaScript objects which display only one value each. The page includes buttons to expand each item and reveal the remaining values. Originally, I used another AJAX call to retrieve individual objec ...

Utilizing a regular expression to target the characters [/ , .] within the ng-pattern validation

I am struggling to come up with a regex pattern that restricts input strings from containing forward slashes, commas, or dots. <form name="myForm"> <div class="col-sm-4"> <input class="form-control" type="text" dat ...

Trouble with Angular toggle switch in replicated form groups

Currently, I have a form group that contains multiple form controls, including a toggle switch. This switch is responsible for toggling a boolean value in the model between true and false. Depending on this value, an *ngIf statement determines whether cert ...