I'm trying to set it up so that an image pops up when I hover over text. I've tried incorporating a few different JavaScripts, but I still can

I'm struggling to display an image on my website. I have the necessary code parts, but it's not working as expected.

function showImage() {
  $('.img').addClass('display');
}

function hideImage() {
  $('.img').removeClass('display');
}

$('.hover-trigger').hover(showImage, hideImage);
.img {
  display: none;
}

.img.display {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p class="hover-trigger">Hover me</p>
<img src="https://picsum.photos/150" class="img">

Answer №1

This unique script is designed to target elements with the class .trg within the wrapping element identified by the id attribute id="wrap". When the mouse hovers over specific target elements, a timer starts running (currently set at 500ms). This time duration is stored in the variable var delay = 500. After the specified time elapses, the script retrieves the data attribute of the target element and generates a new image element. Upon removing the mouse cursor from the target element, all elements with the class .img are removed along with the created image.

By only loading content when it becomes visible, this approach improves site optimization and efficiency.

You can easily customize this code to add a class to an existing element or modify it according to your specific requirements.

Example:

$(document).ready(function () {

    var delay = 500; // <-- delay time in ms
    var wrp = '#wrap';
    var mouseMove;
    var url;
    var el;
    var show = true;

    $(wrp + ' .trg').on('mouseenter', function () {
        mouseMove = new Date().getTime();
        show = true;
        el = this;
        url = $(this).attr('data');
    });

    $(wrp + ' .trg').on('mouseout', function () {
        $('.img').remove();
    });

    setInterval(function () {
        var curTime = new Date().getTime();
        if (curTime - mouseMove > delay && $(wrp + ':hover').length != 0 && show) {
            var img = document.createElement('img');
            img.setAttribute('class', 'img');
            img.setAttribute('src', url);
            el.append(img);
            show = false;
        }
    }, delay);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<div id="wrap">
    <div class="trg" data="https://blog.54ka.org/wp-content/uploads/2020/08/horses-on-summer-meadow_027_by_54ka-165x165.jpg">Lorem 01</div>
    <div class="trg" data="https://blog.54ka.org/wp-content/uploads/2020/08/horses-on-summer-meadow_005_by_54ka-165x165.jpg">Lorem 02</div>
    <div class="trg" data="https://blog.54ka.org/wp-content/uploads/2020/08/horses-on-summer-meadow_006_by_54ka-165x165.jpg">Lorem 03</div>
</div>

Example 2

This particular example illustrates how you can adapt the provided code to suit your needs.

$(document).ready(function () {

    var delay = 500; // <-- delay time in ms
    var wrp = '.hover-me';
    var mouseMove;
    var show = true;

    $(wrp).on('mouseenter', function () {
        mouseMove = new Date().getTime();
        show = true;
    });

    $(wrp).on('mouseout', function () {
        $('.img').removeClass('show');
    });

    setInterval(function () {
        var curTime = new Date().getTime();
        if (curTime - mouseMove > delay && $(wrp + ':hover').length != 0 && show) {
            $('.img').addClass('show');
            show = false;
        }
    }, delay);

});
.img {
    display: none;
}

.show {
    display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<p class="hover-me">Hi</p>
<img src="https://picsum.photos/150" class="img">

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

JavaScript: Efficiently Sorting a Multidimensional Array

Here is the array that needs to be sorted based on the third item: const array = [ [1, "Convention Hall", "Mumbai", 10, "XYZ Company"], [2, "Auditorium", "Delhi", 10, "ABC Company"], [3, "CenterHall", "Bangalore", 10, "ZZZ Company"], ... ...

Retrieve information for AJAX tooltip from a specific URL

I am currently utilizing a script for tooltips. Is there a method available to dynamically load the content of a tooltip from a URL (using dynamic content loaded from a PHP script) rather than specifying the path to an html/php file? For Example What I ...

The expected functionality of sending files via ajax is not happening as anticipated

I am having issues with passing file data along with other inputs to my ajax function. Despite my best efforts, the server is not receiving the files. I'm fairly new to using ajax and Jquery. Below is the code snippet of what I have attempted so far. ...

What is the best way to showcase SVG code as an image using Vuejs?

My API is returning an SVG image as ASCII text code, which I am trying to display on my page. However, instead of the image, I just see a blank space. You can view my attempted solution in this JSFiddle: https://jsfiddle.net/c0p4ku78/ The key parts of th ...

Understanding the time complexity of Object.entries()

Is the complexity of Object.entries() in JavaScript known? According to information from this question, it seems like it could possibly be O(n) if implemented by collecting keys and values as arrays and then combining them together? ...

Ensuring the clickable area of the button aligns perfectly with the button itself and adjusting the arrow position to be

Check out the sandbox here: https://codesandbox.io/s/vigilant-currying-h7c3r?file=/styles.css If you are looking for the classes .line and .arrow, they are what you need. When you create an event, notice how the arrows appear too low, with the clickable a ...

Is there a way to incorporate two Bootstrap navbars on a single page that are of varying heights?

Utilizing Bootstrap 3.0 with dual navbars on a single page that adjust in height using the same variable for both .navbar blocks. Despite attempting to incorporate an additional class to alter the height of the initial navbar, it remains unaffected. Check ...

Is there a method to verify the presence of a message event listener already?

Is there a method to determine if a message event listener is already in place? I am trying to accomplish something similar to this: if(noMessageEventListenerExists) { globalThis.addEventListener('message', async function (data) {}) } I have ...

Is there a way to match a compressed javascript stack trace with a source map to pinpoint the correct error message?

When managing our production server, I have implemented minified javascript without including a map file to prevent users from easily deciphering errors. To handle angular exceptions caught by $exceptionHandler, I developed a logging service that forwards ...

Optimizing SEO with asynchronous image loading

I've been developing a custom middleman gem that allows for asynchronous loading of images, similar to the effect seen on Medium. Everything is functioning smoothly, but I'm uncertain about the impact on SEO. The image tag in question looks like ...

Executing several asynchronous functions in Angular 2

I am currently developing a mobile app and focusing on authentication. In order to display data to the user on my home page, I need to connect to various endpoints on an API that I have created. Although all endpoints return the correct data when tested i ...

Error: Node.js/Express unable to connect to static assets

I recently deployed my Express application to a production server and encountered an issue with serving static assets. All of my assets are located in the /public directory, and I am using the following code to call the static middleware: // config.root ...

Error message "Truffle 'Migrations' - cb is not a valid function"

I created a straightforward smart contract using Solidity 0.6.6 and now I'm attempting to deploy it on the BSC Testnet. Here's what my truffle-config.js file looks like (privateKeys is an array with one entry ['0x + privatekey']): netw ...

What steps should be taken to set up the datatable to sort records in descending order based on the creation date?

In my Rails application, I am utilizing the Datatable plugin to display data on the User index page. The first column in the index page is the created_at field, which displays dates like Mon, 17-Oct-16. I want to sort this column in descending order base ...

Surprising sight of a blank canvas behind the font-awesome icon

Is there a way to remove the unexpected white background that appears when adding a font-awesome icon? Here is the HTML code: <div class="notifications-window" id="close-notifications"> <div class="notifications-header&qu ...

What is the best way to animate my logo using JavaScript so that it scales smoothly just like an image logo

I dedicated a significant amount of time to create a unique and eye-catching logo animation for my website! The logo animation I designed perfectly matches the size of the logo image and can be seamlessly integrated into the site. The issue arises when th ...

Issue with Gijgo grid not updating properly during change event

I'm currently working on an MVC 5 application and I've hit a roadblock with a particular view. This view contains a dropdown menu and a grid (Gijgo-grid). The grid's content is supposed to change based on the selected value from the dropdown ...

Fetching real-time Twitter search feeds through dynamic AJAX requests

Previously, I successfully used JSON to retrieve hash tag feeds from Twitter and Facebook. However, currently the feeds are not updating dynamically, indicating a need for Ajax implementation. Unfortunately, my lack of knowledge in Ajax is hindering this ...

Steps to fix issues with Cross-Origin Read Blocking (CORB) preventing cross-origin responses and Cross Origin errors

var bodyFormData = new FormData(); bodyFormData.set("data", "C://Users//harshit.tDownloads\\weather.csv"); bodyFormData.set("type", "text-intent"); //axios.post("https://api.einstein.ai/v2/language/datasets/upload", axio ...

Choosing to collapse a nested JSON arrangement in a targeted manner

Facing a challenging problem here and feeling clueless on how to tackle it. Any guidance or pointer in the right direction would be highly appreciated. My dataset looks like this: data = { "agg": { "agg1": [ { "keyWeWant": " ...