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

When implementing 'useGlobalGuards' in NestJS, remember to exclude endpoints for enhanced security

After implementing the useGlobalGuards method in my main.ts file, all endpoints now utilize the AuthGuard. This guard triggers a 401 error if a valid auth token is not present in the request header. Previously, I used @UseGuards(AuthGuard) on individual cl ...

I seem to be encountering an issue with the image tag while working with HTML code

I have been studying through freecodecamp.org and this is my first tribute project. Everything has been going well, but I am encountering an issue with the image tag. I need to submit my project online, so I have been trying to input image links from Googl ...

Retrieving Twitter posts using the screen_name parameter in a Node.js environment

I am looking to create a website that allows users to enter the Twitter screen name of any celebrity. When the user clicks on the "show tweet" button, the latest tweet from that screen name will be displayed. I am interested in implementing this feature ...

What could be the reason that the div is not being centered in the middle of the body?

<style> .maincont { width: 8em; height: 8em; background: purple; } body { background: limegreen; display: flex; flex-direction: column; place-content: center; place-items: center; } </style> <body> ...

Utilizing Google Fonts offline without the need for an API

Instead of relying on Google Fonts API to access a variety of fonts for my website, I took matters into my own hands. I downloaded a snapshot of fonts from this GitHub repository: https://github.com/google/fonts and transferred them to my web directory. T ...

I am experiencing an issue where the Flex table is not displaying more than 50 rows

I am experiencing an issue where I can't scroll back up with the scrollbar. The table is dynamically filled with data from a database, and when it gets too long, I am unable to scroll back up. Any suggestions on how to solve this problem? If you need ...

Exploring the Power of Angular Toastr Callback Functions

Hey there! I'm currently working with Angular Toastr to display messages on my screen. I have a setup where only two messages can be open at the same time - one for errors and another for warnings. These messages are persistent and require user intera ...

How can Node.js developers properly utilize PM2 for their projects?

I'm currently contemplating a switch from forever to PM2 as a way to ensure my node application stays up and running. I find myself puzzled by the various recommended methods for initiating a process: $ pm2 start app.js -i 4 # Daemonize pm2 and Star ...

Prevent ESLint from linting files with non-standard extensions

My .estintrc.yaml: parser: "@typescript-eslint/parser" parserOptions: sourceType: module project: tsconfig.json tsconfigRootDir: ./ env: es6: true browser: true node: true mocha: true plugins: - "@typescript-eslint" D ...

Conceal the Slider until Fully Loaded with Slick Slider by Ken Wheeler

I am currently using a slider function called Slick by Ken Wheeler. It is currently being loaded in the footer with just two variables. $('.slickSlider').slick({ dots: true, fade: true }); Currently, ...

Can you explain the meaning of this PHP syntax and why is this variable showing NaN?

Looking for question marks on Google can be quite challenging. Can someone explain this process step by step? $page = isset($_POST['page'])?$_POST['page']:"0"; I believe it means to check if $_POST['page'] is set, use that ...

Angular displays X items in each row and column

I've been struggling with this task for the past 2 hours. My goal is to display a set of buttons on the screen, but I'm facing some challenges. The current layout of the buttons doesn't look quite right as they appear cluttered and unevenly ...

I'm interested in knowing if it's feasible to develop unique jQuery selectors that can navigate ancestors, such as a :closest or :parents selector

As a developer who frequently creates jQuery plugins, I often find myself using custom jQuery selectors like :focusable and :closeto to simplify common filters in my code. For example, the :focusable selector is defined as follows: jQuery.extend(jQuery.e ...

Injection of Angular state resolve into controller fails to occur

I'm attempting to ensure that the value from ui-router's resolve is successfully passed to the controller portalsForUserCtrl. Take a look at the router code below: (function () { 'use strict'; var myApp = angular.module("myApp", ["co ...

Generate TypeScript type definitions for environment variables in my configuration file using code

Imagine I have a configuration file named .env.local: SOME_VAR="this is very secret" SOME_OTHER_VAR="this is not so secret, but needs to be different during tests" Is there a way to create a TypeScript type based on the keys in this fi ...

Having trouble accessing a parsed JSON value in Node.js, encountering 1 error

Currently, I am working on creating a simple news web application as a way to practice utilizing APIs. The particular API that I have chosen for this project is . If you take a look at this JSON object that I am attempting to console.log, you will see the ...

Conquering disparities in standards mode with Javascript

Having an issue with this code snippet: function scrollLeft() { document.body.scrollLeft -= scrollSpeed; } While it works fine in Chrome and Safari, it doesn't seem to work in IE and Firefox. Found out that the problem lies in the fact that Fire ...

Issues with HTML formatting in PHP emails

I am sending an approval/disapproval email to a user. I want to include a button in the email so that when the user clicks it, they can approve or disapprove the request. However, I am facing an issue as I cannot see the button in the mail when I receive ...

Removing an appended value in jQuery: A step-by-step guide

Here is my code that successfully appends the first item: After clicking the "show count" button, a pop-up dialog box will display the count. However, to remove the appended item or refresh the page, additional steps are required. function showcount() { ...

Formatting a pair of elements side by side in MUI Select

Currently, I am tackling the challenge of organizing elements in MUI Select v4. My goal is to display these elements in two columns rather than just one column within the dropdown. Despite attempting to override certain styles within MUI, I have not been ...