Stop CSS tooltip from overflowing outside of the page or window

One issue I am facing is with a CSS-only tooltip that uses a span to display the tooltip when hovering over a link. The problem arises when the link is positioned near the top or side of a page, causing the tooltip to extend beyond the edge of the page.

I'm wondering if there's a way to address this using only CSS, or if I'll need to resort to JavaScript for a solution. I've started experimenting with jQuery, but my preference would be to stick with CSS if possible.

You can view the JSFiddle at https://jsfiddle.net/gtoprh21/12/

Snippet:

$( ".ktooltip" )
.mouseover(function(e) {
   var mousex = e.pageX + 20; //Get X coordinates
   var mousey = e.pageY + 10; //Get Y coordinates
   if((mousey+100)>$(window).height())
   {

    $('.tooltip')
    .css({ top: mousey-100 ,left: mousex })

   }
   else if((mousex+200)>$(window).width())
   {
      $('.tooltip')
    .css({ top: mousey ,left: mousex-200})

   }
   else
    {
   $('.tooltip')
    .css({ top: mousey, left: mousex })

    }
})
.ref, .refs {
  position:relative;
}
/*added a text indent to override indent styles further down*/
.ktooltip {
    display: inline-block;
    text-indent:0em;
}

.ref .ktooltiptext, .refs .ktooltiptext {
  visibility:hidden;
  width: 200px;
  background: #fff;
  border-radius: 6px;
  padding: 5px 5px;
  top: -40px;
  left: 10px;
  border:2px solid grey;
  line-height: normal;

    /* Position the tooltip */
    position: absolute;
    z-index: 1;
}

.ref:hover .ktooltiptext, .refs:hover .ktooltiptext {
    visibility: visible;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>
 <span id="edtxt.trans1" class="tei l">My hope is in a bishop,
 <!--link to a reference -->
   <sup class="ref expl">
     <a href="#edtxt-explnote1" id="reference-to-edtxt-explnote1" class="ktooltip">1</a>
       <!-- lhe reference in a tooltip -->
       <span class="ktooltiptext">According to tradition <span style="name">Nicholas</span> was bishop of Myra in Lycia (south-west Turkey today).</span>
   </sup>
  </span><br>
  <span id="trans2" class="tei l">and in almighty God and his never-ending miracles.</span><br>
  <span id="trans3" class="tei l">Generous Saint Nicholas holds an office,</span><br>
  <span id="trans4" class="tei l">there is a gold symbol in his sign.
    <!-- likn to ref -->
    <sup class="ref expl">
      <a href="#edtxt-explnote2" id="reference-to-edtxt-explnote2" class="ktooltip">2</a>
        <!-- the tooltip -->
        <span class="ktooltiptext"> One of <span style="">Nicholas’s</span> symbols was three <sup>bags</sup> of gold <span style="font-variant: small-caps;">which</span> were the <span style="color: red;">dowry</span> he provided <span style="color: blue;">for</span> three <span style="color: green;">girls</span>
        </span>
    </sup>
   </span><br>
   </p>

Answer №1

Regrettably, achieving optimal tooltip positioning purely with CSS poses a challenge.

Suggested Script Solutions

However, given that you are already utilizing some scripts, I recommend the following solution:

  • Utilize position: absolute to accurately position the .ktooltiptext relative to the .ref,
  • Leverage the .getBoundingClientRect() method for seamless retrieval of tooltip dimensions and positioning,
  • Implement corrections if the tooltip extends beyond the window boundaries,
  • Make necessary adjustments in the CSS styling.

Snippet using only native JavaScript

var ktooltips = document.querySelectorAll(".ktooltip");
ktooltips.forEach(function(ktooltip, index){                
  ktooltip.addEventListener("mouseover", position_tooltip); 
})

function position_tooltip(){
  var tooltip = this.parentNode.querySelector(".ktooltiptext");
  
  var ktooltip_rect = this.getBoundingClientRect();

  var tipX = ktooltip_rect.width + 5; 
  var tipY = -40;                     
  // Position tooltip
  tooltip.style.top = tipY + 'px';
  tooltip.style.left = tipX + 'px';

  var tooltip_rect = tooltip.getBoundingClientRect();
  if ((tooltip_rect.x + tooltip_rect.width) > window.innerWidth) 
    tipX = -tooltip_rect.width - 5;  
  if (tooltip_rect.y < 0)            
    tipY = tipY - tooltip_rect.y;    

  tooltip.style.top = tipY + 'px';
  tooltip.style.left = tipX + 'px';
}
.ref,
.refs {
  position: relative;
}

.ktooltip {
  display: inline-block;
  text-indent: 0em;
}

.ref .ktooltiptext,
.refs .ktooltiptext {
  visibility: hidden;
  width: 200px;
  background: #fff;
  border-radius: 6px;
  padding: 5px;       
  top: -999px;        
  left: -999px;       
  border: 2px solid grey;
  line-height: normal;
  position: absolute; 
  z-index: 1;
}

.ref:hover .ktooltiptext,
.refs:hover .ktooltiptext {
  visibility: visible;
}
<p>
  <span id="edtxt.trans1" class="tei l">My hope is in a bishop,
 <!--link to a reference -->
   <sup class="ref expl">
     <a href="#edtxt-explnote1" id="reference-to-edtxt-explnote1" class="ktooltip">1</a>
       <!-- the reference in a tooltip -->
       <span class="ktooltiptext">According to tradition <span style="name">Nicholas</span> was bishop of Myra in Lycia (south-west Turkey today).</span>
  </sup>
  </span><br>
  <span id="trans2" class="tei l">and in almighty God and his never-ending miracles.</span><br>
  <span id="trans3" class="tei l">Generous Saint Nicholas holds an office,</span><br>
  <span id="trans4" class="tei l">there is a gold symbol in his sign.
    <!-- link to ref -->
    <sup class="ref expl">
      <a href="#edtxt-explnote2" id="reference-to-edtxt-explnote2" class="ktooltip">20</a>
        <!-- the tooltip -->
        <span class="ktooltiptext"> One of <span style="">Nicholas’s</span> symbols was three <sup>bags</sup> of gold <span style="font-variant: small-caps;">which</span> were the <span style="color: red;">dowry</span> he provided <span style="color: blue;">for</span>  three <span style="color: green;">girls</span>
  </span>
  </sup>
  </span><br>
</p>

jQuery Implementation

$(".ktooltip").mouseover(function(e) {
  var tooltip = $(this).siblings('.ktooltiptext'); 
  var tipX = $(this).outerWidth() + 5;             
  var tipY = -40;                                  
  tooltip.css({ top: tipY, left: tipX });          

  var tooltip_rect = tooltip[0].getBoundingClientRect();
  if ((tooltip_rect.x + tooltip_rect.width) > $(window).width()) 
    tipX = -tooltip_rect.width - 5; 
  if (tooltip_rect.y < 0)            
    tipY = tipY - tooltip_rect.y;    

  tooltip.css({ top: tipY, left: tipX }); 
});
.ref,
.refs {
  position: relative;
}

.ktooltip {
  display: inline-block;
  text-indent: 0em;
}

.ref .ktooltiptext,
.refs .ktooltiptext {
  visibility: hidden;
  width: 200px;
  background: #fff;
  border-radius: 6px;
  padding: 5px;       
  top: -999px;        
  left: -999px;       
  border: 2px solid grey;
  line-height: normal;
  position: absolute; 
  z-index: 1;
}

.ref:hover .ktooltiptext,
.refs:hover .ktooltiptext {
  visibility: visible;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>
  <span id="edtxt.trans1" class="tei l">My hope is in a bishop,
 <!--link to a reference -->
   <sup class="ref expl">
     <a href="#edtxt-explnote1" id="reference-to-edtxt-explnote1" class="ktooltip">1</a>
       <!-- the reference in a tooltip -->
       <span class="ktooltiptext">According to tradition <span style="name">Nicholas</span> was bishop of Myra in Lycia (south-west Turkey today).</span>
  </sup>
  </span><br>
  <span id="trans2" class="tei l">and in almighty God and his never-ending miracles.</span><br>
  <span id="trans3" class="tei l">Generous Saint Nicholas holds an office,</span><br>
  <span id="trans4" class="tei l">there is a gold symbol in his sign.
    <!-- link to ref -->
    <sup class="ref expl">
      <a href="#edtxt-explnote2" id="reference-to-edtxt-explnote2" class="ktooltip">20</a>
        <!-- the tooltip -->
        <span class="ktooltiptext"> One of <span style="">Nicholas’s</span> symbols was three <sup>bags</sup> of gold <span style="font-variant: small-caps;">which</span> were the <span style="color: red;">dowry</span> he provided <span style="color: blue;">for</span>  three <span style="color: green;">girls</span>
  </span>
  </sup>
  </span><br>
</p>

You can experiment with any of the provided code snippets to ensure that the tooltip remains well-positioned within the window bounds!


⋅ ⋅ ⋅

An Alternative CSS-Based Approach

If precise tooltip alignment is not a priority, consider this CSS-only solution where no HTML modifications are required:

  • Apply position: relative; to the span elements to serve as reference points,
  • Use position: absolute on the .ktooltiptext,
  • Define top and left properties to control the placement of the .ktooltiptext.

This approach maintains the tooltip's visual style while ensuring it aligns consistently below and to the left of the respective span element, preventing overflow issues.

p span { /* TAKIT: Changed here */
  position: relative;
}

.ktooltip {
  display: inline-block;
  text-indent: 0em;
}

.ref .ktooltiptext,
.refs .ktooltiptext {
  visibility: hidden;
  width: 200px;
  background: #fff;
  border-radius: 6px;
  padding: 5px;       
  border: 2px solid grey;
  line-height: normal;
  position: absolute; 
  top: 20px;          
  left: 0;           
  z-index: 1;
}

.ref:hover .ktooltiptext,
.refs:hover .ktooltiptext {
  visibility: visible;
}
<p>
  <span id="edtxt.trans1" class="tei l">My hope is in a bishop,
 <!--link to a reference -->
   <sup class="ref expl">
     <a href="#edtxt-explnote1" id="reference-to-edtxt-explnote1" class="ktooltip">1</a>
       <!-- the reference in a tooltip -->
       <span class="ktooltiptext">According to tradition <span style="name">Nicholas</span> was bishop of Myra in Lycia (south-west Turkey today).</span>
  </sup>
  </span><br>
  <span id="trans2" class="tei l">and in almighty God and his never-ending miracles.</span><br>
  <span id="trans3" class="tei l">Generous Saint Nicholas holds an office,</span><br>
  <span id="trans4" class="tei l">there is a gold symbol in his sign.
    <!-- link to ref -->
    <sup class="ref expl">
      <a href="#edtxt-explnote2" id="reference-to-edtxt-explnote2" class="ktooltip">20</a>
        <!-- the tooltip -->
        <span class="ktooltiptext"> One of <span style="">Nicholas’s</span> symbols was three <sup>bags</sup> of gold <span style="font-variant: small-caps;">which</span> were the <span style="color: red;">dowry</span> he provided <span style="color: blue;">for</span>  three <span style="color: green;">girls</span>
  </span>
  </sup>
  </span><br>
</p>

Answer №2

Implementing this tooltip design using pure CSS, without the need for JavaScript, may not be the most sophisticated approach, but it is reliable and will always work for you :)

    .ktooltip {
        display: inline-block;
        text-indent:0em;
    }
    
    .ktooltiptext, .ktooltiptext {
    display: none;
        width: calc(100vw - 35px);
        background: #fff;
        border-radius: 6px;
        padding: 5px 5px;
        left: 10px;
        border: 2px solid grey;
        line-height: normal;
        text-decoration: none;
        position: absolute;
        z-index: 1;
    
    }
    
    p {display:inline-block}
    
    .ktooltip:hover + span {
        display: block;
    }
    <p>
     <span id="edtxt.trans1" class="tei l">My hope is in a bishop,
     <!--link to a reference -->
    <div style="display:inline-block">
      <a href="#edtxt-explnote1" id="reference-to-edtxt-explnote1" class="ktooltip">1</a>
         
    <span class="ktooltiptext">According to tradition <span style="name">Nicholas</span> was bishop of Myra in Lycia (south-west Turkey today).</span>
    </div>
    
      </span><br>
      <span id="trans2" class="tei l">and in almighty God and his never-ending miracles.    </span><br>
      <span id="trans3" class="tei l">Generous Saint Nicholas holds an office,</span><br>
      <span id="trans4" class="tei l">there is a gold symbol in his sign.
        <!-- likn to ref -->
          <a href="#edtxt-explnote2" id="reference-to-edtxt-explnote2" class="ktooltip">2</a>
            <span class="ktooltiptext" onclick="return false;"> One of <span style="">Nicholas’s</span> symbols was three <sup>bags</sup> of gold <span style="font-variant: small-caps;">which</span> were the <span style="color: red;">dowry</span> he provided <span style="color: blue;">for</span> three <span style="color: green;">girls</span>
            </span>
       </span><br>
       </p>

https://jsfiddle.net/gtoprh21/72/

Answer №3

Despite requiring a complete recoding, a solution can be implemented using the following approach:

$(".ktooltip").on('mouseover', function(e) {
    var tooltip = $('.ktooltiptext'),
        wt = $(window).scrollTop(), //vertical position of window top
        ww = $(window).outerWidth(), //width of window
        tt = tooltip.offset().top, //vertical position of tooltip
        tl = tooltip.offset().left, //horizontal position of tooltip
        tw = tooltip.outerWidth(); //width of tooltip

    tooltip.css({ 'left': '10px', 'right': 'auto', 'top': '-40px' });

    if(tt < wt) tooltip.css('top', 0);
    if((tl + tw) > ww) tooltip.css({ 'left': 'auto', 'right': 0 });
})

Answer №4

Choice 1) Utilizing the title global attribute

The title attribute provides additional information about an element (appearing as a tooltip).

Documentation: The title global attribute The use of the title attribute presents challenges for:

  • Individuals using touch-only devices
  • Individuals navigating with keyboards
  • Individuals utilizing assistive technology like screen readers or magnifiers
  • Individuals facing difficulties with fine motor control
  • Individuals with cognitive impairments. This is primarily due to inconsistent browser support and the complexities introduced by assistive technology interpreting the browser-rendered content.

span {border-bottom: 1px dashed pink}
<span title="According to tradition Nicholas was bishop of Myra in Lycia (south-west Turkey today).">
Move your mouse over this paragraph to see the title attribute displayed as a tooltip.
</span>

Choice 2) When the text and tooltip have fixed sizes: You can utilize 4 CSS classes to position the tooltip relative to the trigger element. For example:

.tooltip-top {top: -3em}
.tooltip-bottom {top: 0}
.tooltip-left {left: -3em}
.tooltip-right {right: 0}

Answer №5

simply utilize this CSS snippet and substitute it with your own class

.ref .ktooltiptext, .refs .ktooltiptext

.ref .ktooltiptext, .refs .ktooltiptext {
  visibility:hidden;
  width: 200px;
  background: #fff;
  border-radius: 6px;
  padding: 5px 5px;
  top: -15px;
  left: 10px;
  border:2px solid grey;
  line-height: normal;

    /* Position the tooltip */
    position: absolute;
    z-index: 1;
}

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 extract a number from a string in JavaScript?

There are instances in HTML files where a <p> tag displays the price of a product, such as ""1,200,000 Dollar"". When a user adds this product to their cart, I want the webpage to show the total price in the cart. In JavaScript, I aim to e ...

The error message appeared as a result of the bluebird and mongoose combination: TypeError: .create(...).then(...).nodeify is

Recently, I encountered an issue while attempting to integrate bluebird with mongoose. Here's the scenario: I wrote some test code using bluebird without incorporating mongoose, and it worked perfectly. The code looked something like this: A().then( ...

Customizing Sass Bootstrap Variables for Tailored Responsive Designs (Specifically for Mobile or Desktop)

Currently, I am in the process of working on a website that has opted for the adaptive approach, using separate mobile and desktop templates instead of responsive design. Despite this choice, Bootstrap is still being utilized on these templates, loading al ...

Can someone show me how to code a function that transforms my paragraph into an image when I hover over it?

< p id="p1" onmouseover="this.style.color='transparent';flipPara()"> < p id="p2" onmouseover="spookyPara()"> function spookyPara() { document.getElementById("p1").attribute = "All_Images/ghost.png"; } I currently have this code sn ...

Display Numerous Values Using Ajax

Having difficulty showing data from the 'deskripsisrt' table in a modal bootstrap? I have successfully displayed from the 'srtptr' table, but not sure how to proceed with the 'deskripsisrt' table. Here's a snippet from my ...

Use a combination of the reduce and map functions in JavaScript to transform a one-dimensional array into a multi-dimensional array

Below is an array containing mySQL results: [ {"eventId":"84","shootId":"72","clubEventId":"253","clubId":"7"}, {"eventId":"84","sh ...

Interact with PHP by utilizing Jquery to update or remove data using the PUT

I'm running into an issue while trying to utilize Jquery.ajax() with PUT and DELETE methods. I am sending data with the request, but on the PHP side, when I print the request, it shows up empty. $.ajax({ url: 'ajax.php', type: 'DELETE& ...

When the onLeave event of fullPage.js is activated

I am struggling to implement two CSS events when transitioning between sections on a fullPage.js application. To see my current progress, you can view the following fiddle: http://jsfiddle.net/pingo_/67oe1jvn/2/ My objectives are as follows: To modify t ...

The CSS Image Gallery refuses to be centered

.imageContainer{ width: 100%; margin: 0 auto; position: relative; text-align: center; } .imageContainer img{ width: 250px; height: 250px; float: left; } .imageContainer img:hover{ opacity: 0.60; } I am having trouble gett ...

What is the reason javascript struggles to locate and replace strings with spaces in a URL?

Let me begin by sharing the code I'm currently working on so that you can easily follow my explanations. Apologies for the French language used, as this website is being developed for a French-speaking school. I have eliminated irrelevant sections fro ...

Guide on incorporating botframework into a mobile application...?

Recently, I developed a chatbot utilizing the MS bot framework in Nodejs. To display the chatbot in an HTML format without iframes, I incorporated a React Component from the link provided at https://github.com/Microsoft/BotFramework-WebChat. At this point, ...

An object is not defined in the following scenario

I currently have a custom function that includes the following code snippet: 1: var object = get_resource($scope, CbgenRestangular, $stateParams.scheme_id); 2: console.log(object) This function triggers the following code: get_resource = function ($sc ...

Improving the Speed of Ajax Auto Complete

We have implemented an ajax auto complete script in MySQL which functions as follows: <?php $q = strtolower($_GET['term']); if (!$q) return; $q = noescape($q); if (is_numeric($q)){ $q = mysql_query("SELECT * FROM `blah` WHERE `id` LIKE & ...

Getting started with jquery plugins: installation and usage

I have some questions as a beginner. Firstly, I'm interested in obtaining this plugin: Unfortunately, I am having difficulty downloading it and seem to be stuck in a loop. Can someone guide me on the exact steps to download it? Secondly, how do I go ...

Having issues with contenteditable functionality not functioning properly on elements that are dynamically generated

Creating an unordered list dynamically and adding items to it on a button click. Appending it to a section with contenteditable set to true, but encountering issues. The code snippet below demonstrates the process: // Create text input var categoryInput = ...

What could be causing my node server's REST endpoints to not function properly?

Here is a snippet of my index.js file: var http = require('http'); var express = require('express'); var path = require('path'); var bodyParser = require('body-parser') var app = express(); var currentVideo = &apos ...

Transferring data between different elements in a React application

I am currently learning React and facing some challenges in terms of passing data between components. Even after reviewing various tutorials and blogs, I am still struggling to make things work. Within my project, I have two child components named Body-c ...

Convert the array to a JSON format

My goal is to design a form based on a JSON file to store settings. This will make it appear database-driven, while actually being file-driven, which can help set up the database and other configurations easily. I am almost there but struggling with submit ...

Encountering an issue of receiving "Undefined" while attempting to access constant data from a ReactJS file within my NodeJS

I am currently working on a file named check-rates that stores useStates() which are inputs provided by users. These inputs are essential for me to calculate and provide an estimated value for their shipment using the DHL API. In my nodejs express server, ...

The MVC framework causing the Morris chart to omit the final xkey value

I am facing an issue with my Morris Chart where it is not displaying the last xkey value. Any thoughts on why this might be happening? https://i.stack.imgur.com/mHBQd.png Here is the data I am working with: [{"Date":"2016-07-17","Average":0.0},{"Date":" ...