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

The jQuery script is functioning flawlessly in one specific direction

Currently, I am utilizing a basic script to alter the color of elements based on the div being hovered over. While this works smoothly in one direction down the line, when trying to reverse order and backtrack, the colors do not function as intended. The ...

using jquery to send form data to an MVC controller with model binding

I am attempting to send a knockoutjs view model using jquery post var $form = $('#barcodeTemplate form'); var data = ko.toJS(vm.Template); $.post($form.attr('action'), data); The view model consists of basic properties and an array w ...

The status of "Checked" has now been set to untrue

As a beginner, I am struggling to understand how the value changes in my code. Here is a screenshot of the Material UI switch: In the provided code snippet, the value event.target.checked is coming from the following Switch component: <Switch c ...

Having issues with 'direction' in React withStyles causing errors

I am experiencing an issue with my React website where I am using the withStyles feature to apply styles to a material-ui Grid element. Specifically, when attempting to use direction: "column" in the style, I encounter the error message provided below. Th ...

Automatically update div content using AJAX in a different approach

In my situation, I am facing a unique challenge compared to other queries. I have a div element with the following code <div id="ondiv"><?php ?></div> Within this PHP section are details of people who are currently online. Ideally, when ...

Toggle the panel upwards using jQuery's slideToggle function

Looking to create an expandable footer triggered by a click on the '+' sign... Initially, the footer will display basic copyright information and social media links. Upon clicking the sign, I want a sitemap and additional content to slide above t ...

Easy steps to dynamically add buttons to a div

I need help with a JavaScript problem. I have an array of text that generates buttons and I want to add these generated buttons to a specific div element instead of the body. <script> //let list = ["A","B","C"]; let list = JSON.p ...

How to Automatically Display the First Tab in Bootstrap 3

Having a dynamic modal with two tabs, I aim for #tab1 to always be the default tab upon opening the modal. The issue arises when the modal is opened, #tab2 is clicked, and then the modal is closed. Subsequent reopenings still display #tab2. See JSFiddle e ...

Setting up Stylelint in a Next.js project: A step-by-step guide

I'm looking to incorporate Stylelint into my Next.js app. Can I modify the next.config.js file to include the stylelint-webpack-plugin, in order to receive style errors during compilation? // next.config.js module.exports = { reactStrictMode: true, ...

When refreshed, CSS and JavaScript were not loaded

As a newcomer to AngularJs, I am facing an issue that has left me puzzled. I am attempting to create a single-page application using AngularJS + ExpressJS. Everything is functioning properly, but I am encountering a problem upon page refresh. For example, ...

Load Materialize autocomplete with data from a JSON file

After hours of research, I am struggling to populate my autocomplete input using the Materialize plugin for a website project. Since I am not well-versed in json or ajax, implementing the original example from the documentation with static data has been qu ...

Generate a click event on the target page after clicking on an href link

On a source page, there is a collection of links that direct to various documents containing HTML content. Each document has a "print" button within it. I'm looking for a way for clicking on one of the links in the source page to automatically trigger ...

I would like to retrieve my data using my personal API and have them displayed as checkboxes

https://i.sstatic.net/qPSqe.jpgHere is an excerpt of the progress I have made main.html (it's actually a form) <div class="form-group form-check-inline"> <input class="form-check-input" type="radio" name=& ...

When initializing a new instance of Stripe using cartalyst/stripe-laravel, an error occurs stating "The Stripe API key has not been properly defined!"

I am eager to explore Stripe and learn how to process payments. Currently, I am utilizing the cartalyst/stripe-laravel package to create a new instance of Stripe following the instructions provided here. The code snippet should resemble this: $stripe = ...

Tips for altering the design of a registration page

I'm struggling to modify my registration page layout so that the avatar is positioned on the left while the username, password input boxes are on the right. I attempted to use split divs without success and also tried adjusting the positioning of the ...

How can I anchor a div Banner saying "Get 50% off our products" to the Navbar directly above it?

Bootstrap Question: How can I attach the div Banner ("50% off of our products") to the Navbar directly above it? The structure looks like this: <Navbar> </Navbar> <div> <span>Discount: 50% off of our products </span </di ...

Positioning elements in a header using CSS techniques

I am currently working on designing a navigation menu header that includes a logo, along with some buttons aligned to the left side of the logo. However, I am facing an issue where these buttons appear at the bottom of the logo instead of aligning to the t ...

Obtainer that yields the function opposed to a "return" value

For my JavaScript project, I am experimenting with using getters and setters. I'm fetching a JSON object using jQuery's get method and setting the value with a setter. While I can successfully display the content within the setter function throug ...

The value in the dropdown list changes once the page is reloaded

I am facing an issue with the dropdown list that appears on every page of my application's layout. The dropdown contains a list of hotels, and when I select a different hotel from the dropdown, it redirects me to the main page with the updated ID. Eve ...

How can I update a date value received from a v-model in Vue.js when the input type is set to "date"?

My issue lies in the date format coming as "9999-99-99 00:00:00", while I want it to be just "9999-99-99". The dates are stored in an array with multiple fields. How can I update the value using Vue.js? new Vue({ el: '#app', data: () => ...