Is there a CSS property that is determined by the position of an element

My objective is to display a styled tooltip in an HTML document.

To achieve this, I have written the following code:

.word-with-tooltip{
  position:relative;
 }
  
.tooltip{
  position:absolute;
  bottom:1.5em;
  right:0;
  height:100px;
  width:200px;
  display:none;
  border-style:solid;
  border-width:1px;
  border-color:gray;
  background-color:#dddddd;
  text-align:left;
 }

.word-with-tooltip:hover .tooltip{
  display:block;
 }
<div style="height:200px"></div>
  <div>
    <span class="word-with-tooltip">
      Left Car
      <div class="tooltip">A vehicle with four wheels</div>
    </span>
  </div>
  <div style="text-align:center;">
    <span class="word-with-tooltip">
      Centered Car
      <div class="tooltip">A vehicle with four wheels</div>
    </span>
  </div>
<div style="text-align:right;">
  <span class="word-with-tooltip">
    Right Car
    <div class="tooltip">A vehicle with four wheels</div>
  </span>
</div>
<div style="height:200px"></div>

Essentially, this code functions as intended by displaying a nicely formatted tooltip when hovering over a word with the mouse: https://i.sstatic.net/LMDjk.png

However, there is an issue where the tooltip gets cut off when it's positioned too far to the left:

https://i.sstatic.net/lbIPn.png

A potential solution would be to adjust the CSS property from right to left based on the location of the tooltip relative to the screen. Since the position of the tooltip can vary within a large text, this adjustment is necessary for proper display.

Inquiry: Is it feasible (and how) to ...

  1. set the CSS property left:0 if the word is located in the left half of the screen?
  2. set the CSS property right:0 if the word is placed in the right half of the screen?
  3. set the CSS property top:1em if the word is situated in the upper half of the screen?
  4. set the CSS property bottom:1em if the word is found in the lower half of the screen?

Answer №1

Implement JS for interactive tooltips:

document.querySelectorAll(".word-with-tooltip").forEach(word => {
  word.addEventListener('mouseover', e => {
    const tooltip = e.target.children[0]
    if (!tooltip) return;
    tooltip.style.cssText = `
      ${( e.clientX * 100 ) / window.innerWidth < 50 ? 'left' : 'right' }: 0;
      ${( e.clientY * 100 ) / window.innerHeight < 50 ? 'top' : 'bottom' }: 1em;
    `
  })
})
.word-with-tooltip {
  position: relative;
}

.tooltip {
  position: absolute;
  bottom: 1.5em;
  right: 0;
  height: 100px;
  width: 200px;
  display: none;
  border-style: solid;
  border-width: 1px;
  border-color: gray;
  background-color: #dddddd;
  text-align: left;
}

.word-with-tooltip:hover .tooltip {
  display: block;
}
<div style="height:200px"></div>
<div>
  <span class="word-with-tooltip">
      Blueberry Fruit
      <div class="tooltip">A small, round fruit with a sweet flavor.</div>
    </span>
</div>
<div style="text-align:center;">
  <span class="word-with-tooltip">
    Mango Fruit
    <div class="tooltip">A tropical fruit with a juicy pulp.</div>
    </span>
</div>
<div style="text-align:right;">
  <span class="word-with-tooltip">
    Kiwi Fruit
    <div class="tooltip">A fuzzy brown fruit with a green interior.</div>
  </span>
</div>
<div style="height:200px"></div>

Answer №2

Here's a unique solution I discovered: I implemented the following styles:

.word-with-tooltip.left .tooltip{left:0;}
.word-with-tooltip.right .tooltip{right:0;}

These styles were then assigned dynamically within an onmouseover event handler. The code for this implementation is as follows (the content of the onmouseover attribute has been broken down for easier readability):

<div>
<span class="word-with-tooltip"
onmouseover="
this.classList.remove('left');
this.classList.remove('right');
if(event.clientX<window.innerWidth/2){
    this.classList.add('left');
} else {
   this.classList.add('right');
}">
Left Car
<div class="tooltip">A vehicle with four wheels</div>
</span>
</div>

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

Accessing JSON data frequently, even when using an invalid key

My function includes a JSON with key-value pairs, where the key is received as a parameter and the value is the result of another function. The code snippet below illustrates this: const normalizeKeyValuePair = (key, value) => { const propertyHandler ...

Leveraging the post method in Ajax along with a Perl script and passing parameters

I am struggling to utilize the POST method in XMLHTTPRequest by invoking a Perl script with parameters. Despite confirming the validity of these variables (uName, uProject, etc.), and verifying that write.pl functions properly when parameters are manuall ...

Can CSS Variables be changed globally using jQuery?

How can I dynamically change CSS Variables globally using jQuery? Check out this code snippet: $("div").click(function() { // Update the global variable "--text_color: rgb(0, 0, 255);" to a new value like "--text_color: rgb(0, 255, 255);" }); :roo ...

The elements in the navigation bar stay in view for a short period of time even after the collapsible navbar has been

After collapsing the navbar, the navbar items remain visible for a short period of time, as shown in the second image below. Here is the HTML code: <nav class="navbar navbar-dark fixed-top" style="background-color: transparent;> <a class="navb ...

The Vue.js @click event does not function properly when used in a selection on mobile

I designed a dropdown menu with different options, and when one is selected it updates the "Value" in vue to a specific amount. Then, I display the selected amount in an input field. For example: <select class="form-control" style="max-width: 150px;" ...

Invalid Data Pusher for User Information in Next JS

Hello everyone, I've been practicing using Pusher with Next.js but encountered an issue where it's showing Error: Invalid user data: 'presence-channel' and I can't seem to solve it no matter how hard I try. Could someone please he ...

What could be causing the delay in Express when transitioning between console logs while using AngularJS $http.get?

By utilizing Express, Node, and Angular, I incorporated an HTML button on my website that triggers a get request to Express. This request then executes a function that logs a predefined message to the console. Initially, when I click the button for the fir ...

Tips for utilizing navigator.getDisplayMedia with automatic screen selection:

navigator.mediaDevices.getDisplayMedia({ audio: false, video: true }).then(gotMedia).catch(function(e) { console.log('getDisplayMedia() error: ', e); }); Triggering the above code will result in a popup like this. There is anoth ...

Is it possible to utilize JavaScript for transmitting and storing data on a server?

Consider this scenario: When you submit a query on stackoverflow, the data you provide is entered into a text field. This information is then transmitted to the server for storage and eventual display to the user. Is it possible to code the functionality ...

What is the best way to transform an array of lists into a neatly organized state?

I recently received a list of breweries from an API call and I am trying to format it into my React state container. Here is what I have so far: state = { breweries: [ {name: Foo, long: 45, lat: -39.239}, ...

iOS is not recognizing the <a> tag but is instead honoring the :hover property

Within my list, I have a div element wrapped in an anchor tag. Here is an example of the code: <li> <a href="http://google.com/"> <div id="tease-info"> <div class="inset-img-border fade"></div> <img src=" ...

After refreshing, the base href in the environment is characterized as undefined

Within my angularjs application, I have configured the env.js file as shown below: (function (window) { window.__env = window.__env || {}; // API url window.__env.apiUrl = 'http://aaaaaaa.com/'; // Base url window.__env.baseUrl = '/angula ...

Step-by-step guide: Deploying your app to Heroku with Babel and ES6 support

I've been racking my brain trying to deploy the app on Heroku. The issue is with using ES6 along with Babel. I've come across numerous articles, but none have helped me resolve the problem. Even after building the app locally and attempting to ...

In Angular.js, there is a limitation with ng-keyup where event.preventDefault() cannot be utilized, and ng-keypress may have delays when updating the value for an

Issue: The input type number with min and max constraints is not being enforced while typing in the input box. It allows values outside of the specified range to be entered. However, using the arrow buttons of the input type number works fine. Solution Ne ...

The footer seems to be malfunctioning

Let's start with the code: CSS: *{ margin:0; padding:0; } body,html{ height:100%; } body{ background:url('../images/bg.png'); background-position:center; background-repeat:no-repeat; background-attachment:fixed; height:100%; ...

Caution in React: Utilizing functions with Object.assign() may not be a valid approach when dealing with React children

I have a setup using react for front-end and node for back-end. My goal is to retrieve data from the server to update the user entries on the front-end. I came across using Object.assign() as a potential solution to re-render user entries, but encountered ...

The jQuery ajax function is failing to return any results

Here is the code snippet I am working with: $("#MainContent_btnSave").click(function () { if (($("#MainContent_txtFunc").val() == "") || ($("#MainContent_cmbLoc").val() == "")) { alert("Please make sure to fill in all required ...

Limit certain characters within special characters

I have experimented with a regular expression that matches strings containing zero or more occurrences of "%" and "&", but returns false if "@" or "$" is found: ^((%&)*(?!@).)*$ Now, I require a regex pattern to validate strings that must contain ...

Is my website broken due to Internet Explorer?

The progress on my current website project has been smooth so far, but I'm encountering an issue when testing it in Internet Explorer. Whenever I try to view it in IE, the layout breaks completely. You can check it out at . I've attempted using C ...

Incorporating various language URLs in Next.js using next-i18n-next functionality

Thinking about using the next-i18next internationalization library. Check out next-i18next on GitHub Curious about how to change the language in the path of my URL. For example: /about-us /over-ons -> takes you to the Dutch version of the about us p ...