Show image when hovering over individual words

Is there a way to display different descriptions or images when hovering over each word in a paragraph using HTML? It seems that only the last element is being retrieved and displayed across the entire paragraph. Any suggestions on how to fix this issue would be greatly appreciated!

For simplicity, I've included just the code related to displaying text descriptions below, omitting any non-essential parts. If anything is unclear, please feel free to ask for clarification. Thank you for your help.

JSON data:

    var json = {
"parameter1": {'Anyway': 0.822, 'if': 0.91, 'you': 0.53, "don't": 0.9, 'agree': 0.53},
"parameter2": {'Anyway': 0.1322, 'if': 0.4001, 'you': 0.523, "don't": 0.509, 'agree': 0.201},
"parameter3": {'Anyway': 0.822, 'if': 0.101, 'you': 0.423, "don't": 0.225, 'agree': 0.61},
"parameter4": {'Anyway': 0.72, 'if': 0.201, 'you': 0.603, "don't": 0.869, 'agree': 0.99},
"parameter3_text": {'Anyway': "description1", 'if': "description2", 'you': "description3", "don't": "description4", 'agree': "description5"}

}

Part of a switch statement (other parameters omitted):

    case "parameter3":
        for(var x = 0; x < words.length; x++) {

            var span = "<span class='tooltiptext'>" + json.parameter3_text[Object.keys(json.parameter3_text)[x]] + "</span>"
            
            spans.push(span);
        }

        // setting colored spans as paragraph HTML
        paragraph.innerHTML = spans.join(" ");
        break;

HTML code

<div class="parameter3">
    <p id=p3><span>Anyway if you don't agree</span></p>
</div>

CSS code

.parameter3 {
  position: relative;
}

.parameter3 .tooltiptext {
  visibility: hidden;
  width: 120px;
  background-color: white;
  color: #000;
  text-align: center;
  border-radius: 5px;
  padding: 5px 0;
  border: solid;

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

.parameter3:hover .tooltiptext {
  visibility: visible;
  top: 30px;
  left: 20px;
}

Answer №1

In order to achieve the desired effect, you will have to wrap each word in a span element, not just the tooltip/image. Here is an example of how you can do this:

var data = {
"parameter1": {'Item': 0.822, 'if': 0.91, 'you': 0.53, "don't": 0.9, 'agree': 0.53},
"parameter2": {'Item': 0.1322, 'if': 0.4001, 'you': 0.523, "don't": 0.509, 'agree': 0.201},
"parameter3": {'Item': 0.822, 'if': 0.101, 'you': 0.423, "don't": 0.225, 'agree': 0.61},
"parameter4": {'Item': 0.72, 'if': 0.201, 'you': 0.603, "don't": 0.869, 'agree': 0.99},
"parameter3_text": {'Item': "desc1", 'if': "desc2", 'you': "desc3", "don't": "desc4", 'agree': "desc5"}
}

let items = Object.keys(data.parameter3_text);
const spans = [];
const para = document.querySelector("#para3");
for(var x = 0; x < items.length; x++) {

            var span = "<span class='item'>" + Object.keys(data.parameter3_text)[x] + "<span class='tooltip'>" + Object.values(data.parameter3_text)[x] + "</span></span>"
            
            spans.push(span);
        }

        // setting colored spans as paragraph HTML
        para.innerHTML = spans.join(" ");
.parameter3 {
  position: relative;
}

.parameter3 .tooltip {
  visibility: hidden;
  width: 120px;
  background-color: white;
  color: #000;
  text-align: center;
  border-radius: 5px;
  padding: 5px 0;
  border: solid;
  /* Position the tooltip */
  position: absolute;
  z-index: 1;
}

.item:hover .tooltip {
  visibility: visible;
  top: 30px;
  left: 20px;
}
<div class="parameter3">
  <p id="para3"><span>Item if you don't agree</span></p>
</div>

Answer №2

I managed to fulfill your requirements by organizing the markup in the following manner:

<p><span class="word">Anyway<span class="tooltip">0.822</span></span>...</p>

Each word has an outer span that contains an inner span for the tooltip related to that word.

Feel free to explore the demo provided below:

const sentences = [
  { 'Anyway': 0.822, 'if': 0.91, 'you': 0.53, "don't": 0.9, 'agree': 0.53 },
  {'Anyway': 0.1322, 'if': 0.4001, 'you': 0.523, "don't": 0.509, 'agree': 0.201},
  {'Anyway': 0.822, 'if': 0.101, 'you': 0.423, "don't": 0.225, 'agree': 0.61},
  {'Anyway': 0.72, 'if': 0.201, 'you': 0.603, "don't": 0.869, 'agree': 0.99},
  {'Anyway': "description1", 'if': "description2", 'you': "description3", "don't": "description4", 'agree': "description5"}
]
 
 const app = document.getElementById('app')
 
 sentences.forEach(sentence => {
  app.innerHTML += '<p>'
  Object.keys(sentence).forEach(word => {
     app.innerHTML += `<span class="word">${word}<span class="tooltip">${sentence[word]}</span></span> `
  })
  app.innerHTML += '</p>'
 })
.word {
  position: relative;
}

.tooltip {
  background-color: #eee;
  position: absolute;
  bottom: 100%;
  left: 0;
  pointer-events: none;
  opacity: 0;
}

.word:hover .tooltip {
 opacity: 1;
}
<div id="app"></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

Utilizing Selenium and BeautifulSoup to extract data from a website

I am currently in the process of scraping a website that dynamically loads content using JavaScript. My objective is to create a Python script that can visit a site, search for a specific word, and then send me an email if that word is present. Although I ...

Is there a way in WebStorm to create a "virtual" folder for conveniently organizing and hiding config files, or perhaps a feature that allows for easily toggling visibility of certain files?

I have a strong dislike for having all my configuration files cluttering up the root directory. These files are usually set up at the beginning of a project and rarely need to be changed. While I can hide them in WebStorm, it becomes a hassle to unhide the ...

Triggering Events with Angular Checkboxes

I'm having trouble getting a console log to trigger when the user checks one of the checkboxes. The script is working fine for everything else, but checkbox clicks are not registering any events. Any suggestions on why this might be happening? (Just ...

The error message "TypeError: Cannot read properties of undefined (reading 'prototype')" is encountered in Next.js 13 when trying to access the prototype of an

I tried to integrate the downshift library into my project. However, when I attempted to use a basic example from the GitHub repository here, I encountered an error. Current versions: Next.js: 13.2.4 React: 18.2.0 Upon further investigation, it seems lik ...

Is the callback still triggered even after the off function is called?

Can someone help me with a scenario where despite calling the off on a reference, the callbacks are still being triggered repeatedly? var ref = new Firebase('https://example.firebaseio.com/123456'); for (var n = 0; n < 1024; ++n) { ref.pus ...

Can absolute positioning of an element impact the relative positioning of the element below it? What steps can be taken to

The webpage contains rows that are relatively positioned. Each row consists of col1 and col2, which are floated to the left and right, respectively. However, there seems to be an issue with the last row where col1 and col2 are not floating as expected. I ...

Can media queries styles be applied to a window of random size using JavaScript?

Can JavaScript be used to apply media queries style based on random window sizes? I have 5 buttons that I want to switch styles for using JavaScript according to the media queries defined in my CSS stylesheet. Is there a method to achieve this? ...

Trouble with Materialize CSS: Form elements displaying incorrectly

I attempted to implement a login form within a modal, following the example provided here (https://codepen.io/skcals/pen/bxdpaN). However, when I applied the same code to my own website, this is how it appeared: Has anyone else encountered this issue? And ...

PHP and Ajax Form Submission Directing to Backend PHP Script

While working on a portfolio, I encountered an issue with the contact form. When I click the submit button to send a message, instead of displaying the bootstrap alert message below the form, the page redirects to the PHP file. Although I receive the emai ...

In CAKEPHP, emphasize a row in a Product table to indicate a comparison condition, without the need for hovering

I've been experimenting with different approaches to make this comparison work. Despite trying various methods, only the "gumboots" string check seems to do the trick. This string represents a product name in the table and proves that PHP is not neede ...

What is the best way to retrieve the total number of nested objects within an object?

I'm trying to figure out how to get the number of nested objects in the object a. a = { firstNested: { name: 'George' } secondNested: { name: 'James' } } I thought about using .length, which is typ ...

Extension Overlay for Chrome

I'm currently working on developing a Chrome extension, but I'm encountering some confusion along the way. Despite researching online, I keep receiving conflicting advice and haven't been able to successfully implement any solutions. That&ap ...

Displaying a table in Chrome/Firefox with a mouseover feature

Hovering over the rows of this table triggers a display of descriptions. html: <tr title="{{transaction.submissionLog}}" class="mastertooltip">... JavaScript: $('.masterTooltip').hover(function(){ // Hover functionality ...

Styling Text with Shadow Effects in Mobile Web Browsers

I'm attempting to apply a text-stroke effect using text-shadow like this: .text-stroke { text-shadow: -1px -1px 0 white, 1px -1px 0 white, -1px 1px 0 white, 1px 1px 0 white; } Unfortunately, it's not rendering correctly on mobile versions of Fi ...

Remove any unnecessary white space and new lines from the HTML code

Is there a way to remove double whitespaces and new lines from my HTML output without altering the ones within textarea and pre tags using PHP? ...

Bootstrap sliders stagnant and unresponsive

I am encountering an issue with my bootstrap carousel slide. I have configured the buttons and set it to slide automatically, but for some reason, the carousel is not moving when I click on the buttons. I can't figure out what mistake I might be makin ...

What is the best way to customize the appearance of the material-ui select component using styled-components instead of material-ui classes in a React

I've been facing some challenges while trying to style my material-ui select component using styled-components instead of material- classes. The version I am working with is material-ui/core 4.12.3. When I use the old makeStyles component from materi ...

Sorting the output with gulp and main-bower-files (gulp-order is not functioning)

Hello, I'm a Java engineer diving into the world of Javascript for the first time. Apologies in advance if my information is lacking or incorrect! I am currently working on a gulp build script and utilizing bower to manage dependencies for my JS fron ...

Buttons for toggling D3 bubble chart display mode

As a beginner in D3.js, I am exploring the creation of a bubble chart with a toggle button to switch between different presidential campaign candidates. While I succeeded in making the chart for one candidate, I am encountering difficulties implementing th ...

How can I expand the notification pop-up in R Shiny?

I'm trying to figure out how to expand the notifications in R Shiny because right now they are cutting off longer error messages. Any suggestions? library(shiny) ui <- fluidPage( actionButton("test", "Test") ) server <- f ...