Display an image when the cursor hovers over a text

I'm attempting to display an image when hovering over specific text. The image should not replace the text, but appear in a different location.

The concept is as follows: When hovering over the word "Google", the Google logo should appear in the red box, and when hovering over the word "OneNote", the OneNote logo should appear in the red box. Step 1

I attempted to achieve this with the following method:

<!DOCTYPE html>
    <head>
        <meta charset="utf-8">
        <title>test</title>
    </head>
    <body>
        <img id="img1" onmouseover="setImg()" onmouseout="unSetImg()" src="https://i1.wp.com/www.grapheine.com/wp-content/uploads/2015/09/nouveau-logo-google.gif?fit=1950%2C1200&quality=90&strip=all&ssl=1" width="300">
    </body>
    <script type="text/javascript">
        function setImg(){
            document.getElementById("img1").src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSU48ifXX9Kar3IFVrlfwx6UFLqaQno8rCebFvGtwk6yWky9_mz";
        }

        function unSetImg(){
            document.getElementById("img1").src="https://i1.wp.com/www.grapheine.com/wp-content/uploads/2015/09/nouveau-logo-google.gif?fit=1950%2C1200&quality=90&strip=all&ssl=1";
        }
    </script>
</html>

While this approach works when replacing one image with another, it does not work when trying to replace an image with text.

If anyone can suggest a solution that aligns with my desired outcome, I would greatly appreciate it!

Thank You

Lucas

Answer №1

To enhance user experience, consider storing the img src in a data-attribute on the element that will be hovered. Upon hover, set the img.src to the data-logo value of the hovered element.

var elems = document.querySelectorAll("#thing li");
var logo = document.querySelector("#thing .logo");
elems.forEach(function(elem) {
  elem.addEventListener("mouseover", function() {
    logo.src = elem.getAttribute("data-logo");
  });
  elem.addEventListener("mouseout", function() {
    logo.src = "";
  });
});
img.logo {
  border: 2px dotted red;
  height: 50px;
  min-height: 50px;
  min-width: 50px;
}
<div id="thing">
  <img class="logo" />
  <ul>
    <li data-logo="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png">Google</li>
    <li data-logo="https://learn.microsoft.com/en-us/graph/images/onenotelogobgs.png">OneNote</li>
  </ul>
</div>

Answer №2

.hovercontainer {
            width: 500px;
            margin: 0 auto;
            position: relative;
            height: 170px;
        }
                  .hovercontainer p{
                    position:absolute;
                    top:50%;
                    text-align: center;
                    left:0;
                    right:0;
                    margin:0 auto;  
                    z-index:10;
                  }
        .hovercontainer img{
        width:90%;
        -webkit-transition: all .3s ease-in-out;
        -moz-transition: all .3s ease-in-out;
        -ms-transition: all .3s ease-in-out;
        -o-transition: all .3s ease-in-out;
        transition: all .3s ease-in-out;
        opacity:0;
                  position: relative;}
        .hovercontainer p:hover ~ img{
        opacity:1
        }
                  .hovercontainer p:hover{
                    opacity:0;
                  }
    <div class="hovercontainer">
                    <p>Text</p>
                    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSU48ifXX9Kar3IFVrlfwx6UFLqaQno8rCebFvGtwk6yWky9_mz" alt="" />
                    </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

Is there a way to display an asterisk within a select2 dropdown to signify that a field is mandatory?

I'm facing an issue with the Select2 plugin in my form. While all fields are required and marked by an asterisk when empty, the Select2 dropdown ignores this validation attribute. Therefore, I am wondering: Is there a way to display an asterisk image ...

I'm struggling to convert this vertical navigation bar into a horizontal layout using CSS

<nav class="navbar navbar-dark bg-dark sticky-top"> <a class="navbar-brand" href="#">I/H</a> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item active"> ...

The request for the URL (https://deno.land/std/encoding/csv.ts) could not be sent due to an operating system error with code 100

Encountering an issue with importing the stdlib files from deno.land to the local cache when running mod.ts. Error: error sending request for url (): error trying to connect: tcp connect error: An attempt was made to access a socket in a way forbidden by ...

The looping function in JavaScript iterates 20 times successfully before unexpectedly producing NaN

run = 0 function retrieveItemPrice(id){ $.get('/items/' + id + '/privatesaleslist', function(data){ var htmlData = $(data); var lowestPrice = parseInt($('.currency-robux', htmlData).eq(0).text().replace(',& ...

How do you manage conditional formatting within HTML forms?

On one of my HTML pages, I am using the following code snippet: {% for bet in recent_bets %} {% if bet.status__name == "Won" or bet.status__name == "Half Won"%} <div class="container col recent-form_col bg-success" data-toggle="tooltip" da ...

"Encountering a glitch with masterpage.cs in Aspx.net and C#

Currently facing a perplexing issue while developing a website using aspx.net and c#. The following code snippet is on my masterpage: protected void Page_Load(object sender, EventArgs e) { if (HttpContext.Current.Request.Url.AbsolutePath == "/ ...

Firefox consistently reports ajax status as error

One of my ajax requests is causing some confusion. $.ajax({ url: webURL, type: 'post', data: somedata, cache: false, datatype: "json", contentType: "application/json", success: successFunc, ...

Is there a way to transform a callback into promises using async/await, and convert a prototype function into a standard

I need help converting a code callback function to promises. When attempting to convert the prototype to a normal function, I encounter an error that I can't fix on my own. I am eager to utilize the ES7 async-await feature to avoid callbacks. functio ...

The contents of Ionic views are not stored in a cache, so the controller must

In my ionic application, I have several views. When I launch the app, it takes me to the main view where data is loaded upon initialization of the controller. The issue arises when I navigate away from this view using tabs; sometimes the controller gets d ...

Exploring the capabilities of the Scripting.FileSystemObject within the Microsoft Edge browser

With the removal of ActiveXObject in Microsoft Edge, what is the alternative method to use FileSystemObject in this browser? I am currently working on developing a Microsoft Edge plugin that captures the HTML code of a web page and saves it as a .txt fil ...

Assign an identifier to the HTML helper Html.EditorFor

When using a textbox created with the HTML helper "@Html.EditorFor", there may be a need to perform some action with JavaScript on its change event. In order to do this, an ID needs to be set for the textbox. For example, if you need to set a string value ...

Executing a NestJs cron job at precise intervals three times each day: a guide

I am developing a notifications trigger method that needs to run three times per day at specific times. Although I have reviewed the documentation, I am struggling to understand the regex code and how to customize it according to my requirements! Current ...

Downloading multiple files concurrently in Flask

I am currently working on implementing a feature in Flask that allows users to download files from the client side. This feature should support downloading multiple files or just a single file. However, I am facing a challenge in providing the option to d ...

Resolve the issue of autofill data overlapping with field labels

My form incorporates the Canada Post AddressComplete tool, which functions similarly to Google Maps Autocomplete. As you type your address, suggestions appear in a drop-down menu. However, after selecting an address, the text in the Postal Code and City f ...

Setting up AngularJS can be a pain

Greetings, my name is Rahim. While setting up AngularCLI, I ran into the following issue: 'ng' is not recognized as an internal or external command, operable program or batch file. C:\Users\ASUS ROG>ng --version 'ng' is ...

How to transfer data from PHP to JavaScript using Ajax in the webpage_BODY

I am extracting data from my Controller and passing it to a Javascript file via the Ajax success function. This data is then utilized to create charts. Here is an example of my controller logic: $result =array( "PourcentageCommande" => $Pourcen ...

What is the best way to center my navigation bar without interfering with the mobile version's JavaScript functionality?

Just starting out with web development and stack overflow, so please bear with me if I struggle to explain the issue. I came across some JavaScript to make my website responsive on small screens (mobiles). However, I am having trouble centering my top nav ...

Encountering the error message "Uncaught TypeError: $.ajax is undefined"

Recently, I encountered an issue with my form that utilizes ajax to send user information to a php file. The form is embedded within a bootstrap modal and was functioning perfectly until I attempted to add an extra field for enhanced functionality. However ...

Grin schedule module JSON stream

I have integrated a Smile timeline widget on my website and successfully customized it following several tutorials. However, I am struggling to utilize a Json service instead of relying on data stored in a global variable within a JavaScript file. Despite ...

The latest version of Material UI icons caused compatibility issues with React-Select

I recently made the switch from using @material-ui/icons version 4.11.2 to @mui/material and @mui/icons-material version 5.2.3 Although material UI is not directly integrated with react-select, there seems to be some interaction happening. The transition ...