Adjust the tooltip image alignment to be offset from the cursor and appear at the bottom of the page

After creating a code snippet for image tooltips on text hover, I encountered an issue on my website where the bottom of the page expanded to accommodate the images. Is there a simple way to align the cursor at the bottom of the image when scrolling to the bottom of the page?

this.imageTooltip = function() {
  /* CONFIG */

  xOffset = 10;
  yOffset = 20;

  // set the distance of the tooltip from the cursor
  /* END CONFIG */

  jQuery("a.tooltip").hover(
    function(e) {
      this.t = this.title;
      this.title = "";
      jQuery("body").append("<p id='tooltip'>" + this.t + "</p>");
      jQuery("#tooltip")
        .css("top", e.pageY - xOffset + "px")
        .css("left", e.pageX + yOffset + "px")
        .fadeIn("fast");
    },
    function() {
      this.title = this.t;
      jQuery("#tooltip").remove();
    }
  );
  jQuery("a.tooltip").mousemove(function(e) {
    jQuery("#tooltip")
      .css("top", e.pageY - xOffset + "px")
      .css("left", e.pageX + yOffset + "px");
  });
};

// initialize the script on page load
jQuery(document).ready(function() {
  imageTooltip();
});
#tooltip {
  position: absolute;
  background: transparent;
  color: #333;
}

#tooltip img {
  height: 51.5vh;
  width: auto;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<a href="#" class="tooltip" title="<img src='https://s.aolcdn.com/hss/storage/midas/2ff6b684c6195e0bf24e5b5d35e85a4a/205063011/Commodus.jpeg'/>">SAMPLE TEXT</a>
<br>
... (additional sample text links with image tooltips)

Answer №1

To determine if the tooltip will extend beyond the scroll bottom, you can check its height and adjust the offset accordingly. Here is an example that seems to solve this issue:

this.tooltip = function() {
  /* CONFIG */

  xOffset = 10;
  yOffset = 20;

  // calculate the distance between the cursor and the tooltip
  /* END CONFIG */

  jQuery("a.tooltip").hover(
    function(e) {
      this.t = this.title;
      this.title = "";
      jQuery("body").append("<p id='tooltip'>" + this.t + "</p>");
      var scrollBottom = $(window).scrollTop() + $(window).height();
      if(scrollBottom <= (e.pageY + $('#tooltip').height()))
           xOffset = $('#tooltip').height();
      else
           xOffset = 10;
      jQuery("#tooltip")
        .css("top", e.pageY - xOffset + "px")
        .css("left", e.pageX + yOffset + "px")
        .fadeIn("fast");
    },
    function() {
      this.title = this.t;
      jQuery("#tooltip").remove();
    }
  );
  jQuery("a.tooltip").mousemove(function(e) {
    jQuery("#tooltip")
      .css("top", e.pageY - xOffset + "px")
      .css("left", e.pageX + yOffset + "px");
  });
};

// run the script when the page loads
jQuery(document).ready(function() {
  tooltip();
});
#tooltip {
  position: absolute;
  background: transparent;
  color: #333;
}

#tooltip img {
  height: 51.5vh;
  width: auto;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<a href="#" class="tooltip" title="<img src='https://s.aolcdn.com/hss/storage/midas/2ff6b684c6195e0bf24e5b5d35e85a4a/205063011/Commodus.jpeg'/>">TEXTS</a>
<br>
<a href="#" class="tooltip" title="<img src='http://justsomething.co/wp-content/uploads/2013/11/guns-replaced-thumbs-up-18.jpg'/>">TEXTS</a><br>

Answer №2

To ensure tooltips are positioned correctly, it's important to check their position relative to the document height using jQuery's offset() method. If a tooltip extends beyond the document height, adjustments should be made to its position.
For example:

if ( (e.pageY - xOffset + tooltip image height) > document height )
{
    jQuery("a.tooltip").mousemove(function(e) {
        jQuery("#tooltip")
          .css("bottom", e.pageY - xOffset + "px")
          .css("left", e.pageX + yOffset + "px");
      });
}

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 refresh a .ejs page with updated information following an ajax request

I am in need of re-rendering my homepage.ejs with new data on the server side following an ajax request. Although I am aware that you can somehow re-render the elements in the ajax callback, I am interested in finding out if it is possible to simply re-ren ...

Jquery issue: Lightbox unexpectedly closing by itself :(

Help needed: My light box is closing automatically within seconds. $(document).ready(function(){ $('.lightbox').click(function(){ $('.backdrop, .box').animate({'opacity':'.50'}, 300, 'linear'); ...

Framer Motion's AnimatePresence feature fails to trigger animations when switching between pages

I'm running into issues with the Framer Motion library, specifically with the AnimatePresence transition. I've managed to make it work in normal situations, but when I encapsulate my Routes within a custom implementation, the exit animation fails ...

Encountering an error message saying "assignment to undeclared variable"

I'm attempting to incorporate a react icon picker from material-ui-icon-picker However, I keep encountering an error stating "assignment to undeclared variable showPickedIcon" edit( { attributes, className, focus, setAttributes, setFocus, setState ...

Sending a JavaScript function as part of an ajax response

I'm currently working on a system where the user can submit a form through AJAX and receive a callback in response. The process involves the server processing the form data and returning both an error message and a JavaScript function that can perform ...

Implementing XOR operation in a jQuery script

In need of a small script modification where one value needs to be XORed. A previous suggestion no longer applies due to changes made in the script. <input type='button' value='Ein / Aus' class='taster' csv='Lampe&apo ...

The JQuery duplication process did not function as anticipated

This question builds on a previous one related to jQuery cloning and incrementing IDs. The issue is that when adding new elements, the IDs are not being generated in the correct sequence. For example, if the initial ID is expy-1, clicking "add more" should ...

How can I use AngularJS to initiate code to run after the view and controller have successfully synchronized a specific change?

I am currently using AJAX to load date ranges into a pair of SELECTs (managed with AngularJS ng-repeat), which are then transformed into a slider using jQuery UI's selectToUISlider. My concern is that selectToUISlider may behave unexpectedly if the SE ...

Unable to achieve horizontal alignment with DIV element set as inline-block

Currently, I have five columns that are aligned using the display:inline-block. Everything seems to be working fine, but there's a peculiar issue that arises when I refresh the page multiple times. Occasionally, while the first column remains at the t ...

Is there a way to retrieve a promise from a function that triggers a $http.get request in AngularJS?

Looking for a solution to modify this function: getX: function ($scope) { $http.get('/api/X/GetSelect') .success(function (data) { ... ... }) .error(function (data) { ...

Design interactive elements such as buttons and input fields inspired by the layout of Google websites

Does anyone know how to achieve the sleek, lightweight buttons and text boxes seen on Google's web pages like Google Search, Google Plus, and Google Play? I am currently using JSP and CSS, but I am open to incorporating jQuery if necessary. Any help w ...

Automatically format text fields to display time in hh:mm format from right to left as you type

Is there a way to automatically format hh:mm as the user types in a text field? The default format is 00:00, and I would like it to fill the minutes part when the first two characters are entered, followed by filling the hour part with the third and four ...

A pale tooltip with a light arrow appearing against a soft white backdrop

Can someone help me figure out how to display a white tooltip with a white arrow? I've tried to implement it using the code below, but the white color is not visible against the background. Any suggestions on making it stand out? $(function () { ...

The integration of Laravel (Homestead) Sanctum is malfunctioning when combined with a standalone Vue application

After running the command php artisan serve my Laravel application successfully resolves on localhost:8000. I have configured Laravel Sanctum as follows: SESSION_DRIVER=cookie SESSION_DOMAIN=localhost SANCTUM_STATEFUL_DOMAINS=localhost:8080 As for m ...

Issue with Electron-vue: 'compute:' not functioning as expected

My attempt to create a simple example using the element-ui library was not successful. There are two 'switches' with different active state values: 2 and 1. The values of the switches are supposed to be displayed in <p>{{sw1}}</p> and ...

Guide to storing user data retrieved from the LinkedIn API into an Angularjs controller with the help of a personalized service

Hey there, I'm currently diving into Angular and facing a challenge with saving user information from LinkedIn API to the controller's scope without directly passing it to my custom service. It seems like that might not align with the best practi ...

What is the best way to showcase all menu and submenu items in separate dropdown lists?

Having trouble with my code, it's not functioning properly. I can't pinpoint the error. The menu displays correctly but the submenu isn't showing up under specific menus. Here is the code snippet: ##Table: menus## id name ...

The CSS div mysteriously vanishes right before I can trigger the click event

My CSS code looks like this: #searchbar-wrapper input#header-searchbar:focus + #search-dropdown-wrapper { display: block; } The purpose of this code is to make a dropdown visible when a user focuses on a textbox. The default behavior should be th ...

Is there a way to customize the Webpack output to incorporate specific options solely for a particular bundle?

Currently, I am using Webpack 4 to build multiple bundles. My requirement is to add the output options libraryTarget and library for a single bundle only. The default configuration looks like this: output: { path: path.resolve(__dirname, 'dist/j ...

The framework for structuring web applications using Javascript programming

While I have extensive experience in PHP and C# programming, my knowledge of Javascript is limited. When it comes to server side programming, MVC is my preferred method as it allows me to keep my code well-organized. However, when it comes to writing Java ...