Display an AJAX div when the image is hovered over and have it track the movement of

I am seeking assistance with my website project, which involves providing users with download links to movies.

However, I am struggling to make the preview_block div(id) appear when the mouse hovers over the movie_block div(id). Additionally, I am having difficulty getting the preview_block div to follow my mouse when hovered.

Furthermore, I am looking to implement an AJAX request on the preview_block div to retrieve information about the movie being hovered over.

Below is the code snippet:

For a simpler example, check out this fiddle: https://jsfiddle.net/o4xcb9m0/1/

<!DOCTYPE html>
<html>
    <head>
        <link href="includes/styles.css" />
    </head>
    <body>
        <div class="">
            <div id="preview_block" style="display:none"><p>test</p></div>
            <table>
                <!-- -->
                <tr>
                    <td>
                        <a href="download-link"><span id="movie_block"><img src="image-link" alt="<?php echo $movieNameList->data->movies[0]->title; ?>" /></span></a>
                        <br>
                        <a href="download-link">Movie Name</a>
                        <br>
                    </td>
                    <td>
                        <a href="download-link"><span id="movie_block"><img src="image-link" alt="<?php echo $movieNameList->data->movies[0]->title; ?>" /></span></a>
                        <br>
                        <a href="download-link">Movie Name</a>
                        <br>
                    </td>
                </tr>
                <!-- -->
                <tr>
                    <td>
                        <a href="download-link"><span id="movie_block"><img src="image-link" alt="<?php echo $movieNameList->data->movies[0]->title; ?>" /></span></a>
                        <br>
                        <a href="download-link">Movie Name</a>
                        <br>
                    </td>
                    <td>
                        <a href="download-link"><span id="movie_block"><img src="image-link" alt="<?php echo $movieNameList->data->movies[0]->title; ?>" /></span></a>
                        <br>
                        <a href="download-link">Movie Name</a>
                        <br>
                    </td>
                </tr>
            </table>
        </div>

        <script src="includes/scripts.js"></script>
    </body>
</html>

Answer №1

To enhance the functionality of your code, consider using mouse enter and leave events instead of hover events. This will ensure that the events do not react to event bubbling and treat the entire HTML element as one solid block.

For a detailed explanation, refer to the interactive demo on jQuery mouseover docs at the bottom of the page.

Remember to replace all instances of id="movie_block" with class="movie_block" to maintain the uniqueness of IDs within an HTML document.

$(".movie_block").on({
    mouseenter: function(event) {
        $("#preview_block").css({top: event.clientY, left: event.clientX}).show();
    },
    mouseleave: function() {
        $("#preview_block").hide();
    }
});

Check out this demo for the working code example.

If you want the preview block to follow the mouse pointer, you can use the following modification:

$(".movie_block").on({
    mousemove: function(event) {
        $("#preview_block").css({top: event.clientY, left: event.clientX}).show();
    },
    mouseleave: function() {
        $("#preview_block").hide();
    }
});

View this demo for the updated functionality.

Answer №2

It appears that instead of using the hover event, you should consider utilizing the mousemove event http://api.jquery.com/mousemove/

If you need to get coordinates in HTML when interacting with the mouse, check out this resource: How to get the coordinates in html using .hover event in jquery?

Keep in mind that the hover event does not continuously fire, which means it may not track the mouse movement accurately. For more details, refer to: How to get the coordinates in html using .hover event in jquery?

To ensure your code is clean and easily understandable for others to assist, try sharing it on a platform like jsFiddle:

https://jsfiddle.net/o4xcb9m0/1/

<html>
    <body>
        <div class="">

            <a href="foo.com" >Foo
                <span class="movie_block">
                    Bar
                    <img src="foo" />
                </span>
            </a>      
            <div class="preview_block" style="display:none"><p>test</p></div>
        </div>

        <script>
            $(".movie_block").hover(function(event) {
                $(".preview_block").css({color: 'red', top: event.clientY + 'px', left: event.clientX + 'px'}).show();
            }, function() {
                $(".preview_block").hide();
            });
        </script>
    </body>
</html>

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

Exploring the world of asynchronous operations with React Hooks

Hello, I am a beginner when it comes to React and JavaScript. I could really use some assistance with two hooks that I have created: useSaveStorage and useGetStorage. The issue I am facing is that my app is supposed to receive data and save it into AsyncS ...

Cross-Origin Resource Sharing (CORS) in Ajax requests

I've been attempting to fetch variables from an external domain using AJAX and then populate pre-filled form fields with the retrieved data. However, I'm facing difficulties getting it to function properly. While I'm relatively new to JavaS ...

issues with conditional statement

I'm encountering an issue with the if statement not functioning as expected, and I can't seem to figure out why. The if condition always gets displayed regardless of the input. To troubleshoot, I initially used a temporary code snippet for the co ...

Tips for effectively utilizing the count() function within selenium's xpath feature?

By utilizing the count() function within XPath, we can extract the total count of matching nodes instead of using findElements() and size() methods. Do you know if the count function in XPath returns an integer value? For example, Let's say my xpath ...

How can I retrieve the file name and any other requested parameters in the serveResource method using an ajax call?

I'm currently utilizing ajax to submit the data on my jsp page in a liferay custom portlet without needing to refresh the entire page. Unfortunately, I've encountered two issues with this approach: Although the Ajax function successfully pas ...

What is the best method for choosing all options in a select box in IE without experiencing the scrolling effect?

Here's the scenario: I have a select element with multiple options and a checkbox that allows users to select/deselect all options. The issue arises in Internet Explorer, where selecting all options using code causes the entire select box to scroll un ...

JavaScript error occurring when trying to validate Ajax response

I am attempting to create a report using a dynamically generated form. The form loads successfully through XMLHttpRequest, but the validation for the form fields does not seem to be working. I have experimented with using eval() and found that it only work ...

Resolving Node.js Absolute Module Paths with TypeScript

Currently, I am facing an issue where the modules need to be resolved based on the baseUrl so that the output code is compatible with node.js. Here is my file path: src/server/index.ts import express = require('express'); import {port, database ...

Generate a loop specifically designed to execute the code following the menu in the script

My website has the code snippet below: let txt_com = document.querySelector(".text_user"); let num_com_user = document.querySelector(".massage_for_user"); txt_com.addEventListener("click", function() { if (this.classList.contains("num_com_user")) { ...

Creating an interactive flip card using HTML and CSS

I am a beginner in HTML and I'm looking to create a specific element that flips. I have created this file. However, when the first element is flipped (refer to the codepen), the content appears at the bottom (see image). Can someone assist me in ensu ...

Using a loop to chain jQuery's .when().then() method and ensuring a fixed final call at the end of the

The solution that closely matches my issue can be found at One common use case for .then is chaining ajax requests: $.ajax({...}).then(function(){ return $.ajax({...}); }).then(function(){ return $.ajax({...}); }).then(function(){ retu ...

How to convert deeply nested object structures containing arrays in JavaScript

Despite the less-than-desirable name of this inquiry, the question is fairly straightforward. I have a particular object: let test = { date1: [ { time: 1, value: 5, }, { time: 2, value: 6, }, ], date2: [ { ...

"Assigning a CSS class to determine the length of a List in a JSP

In my JSP code, I have a list called ${contentList} that contains product information such as product images, names, and prices. To display this data in an HTML table using JSP, I want to dynamically set the class of the first table row based on the numbe ...

What is the process for calculating the total sum of input values utilizing JavaScript?

My JavaScript skills are not perfect, and I'm struggling to calculate the total sum of values in the amount input boxes without refreshing the page. Can someone assist me with this challenge? Thank you. function Calculat ...

Identifying the various types in Typescript

In the process of developing a solution for Excel involving data from an Office API, I encountered the challenge of distinguishing between different types that a function can return. Specifically, the data retrieved as a string may belong to either a "Cell ...

Utilizing AJAX to call a partial view

Here is the snippet of code showing my ajax call to a partial view after some processing: function fetchData(data) { $.ajax({ url: "/Orders/DraftOrderDetailsLineItems", type: 'GET', cache: false, dataType: 'html', d ...

Managing events with classes

I have multiple divs with the same class. When one of these divs is clicked, I want to change the display of the other divs to 'block'. Currently, I am using inline JavaScript for this functionality, but I would like to achieve it without inline ...

Creating unit tests without relying on a testing framework: A guide

My goal is to unit test a simple function using pure JavaScript: NS.isType = function (type, obj) { if (obj.constructor && obj.constructor.name) { return obj.constructor.name === type; } return toString.call(obj) === '[obj ...

Problem with X-editable clicking functionality on Chrome browser

Bootstrap version 3 Having trouble with X-editable inline mode - the button click is not hiding the inline form if there are no changes in the field. I found some older discussions about this issue in the thread linked below, but they are from 8 months ag ...

Is the use of div:after content really affecting the width? I am having trouble getting my transition to work

Here is a simple code snippet that represents my actual code: #myDiv { background: black; color:white; float:left; min-width:45px; max-width:450px; -webkit-transition: all 1s ease-in-out; transition: all 1s ease-in-out; } #myDiv:hover:after { width ...