Using Javascript and AJAX to create a floating image beside the cursor - inquiries

I've come across a JavaScript code that allows for a floating image to appear next to the mouse pointer. With the use of PHP, it displays the full-size image that the mouse is hovering over, even if the image on the page itself is slightly downsized. The problem arises when the image is positioned on the right side of the page.

Take a look at the code below:

<script>
var cX = 0; var cY = 0; var rX = 0; var rY = 0;
function UpdateCursorPosition(e){ cX = e.pageX; cY = e.pageY;}
function UpdateCursorPositionDocAll(e){ cX = event.clientX; cY = event.clientY;}

// More code here...

//-->
</script>

Here is a simple example of an image triggering the floating content:

<a onmousemove="ShowContent('FloatingImage','image.jpg'); return true;" href="javascript:ShowContent('FloatingImage','image.jpg')">standard html</a>

<div 
   id="FloatingImage" 
   style="display:none;">  
<img id="MouseImage" name="MouseImage" src="LR-10.jpg" />
</div>

--end code--

While this code works well on its own, it poses an issue when the thumbnail image is on the right side and the floating image goes off-screen. Is there a way to modify the JS code so that the image appears on the left side of the mouse pointer instead?

Another concern: When I integrate this code into my website design using AJAX to load the page inside a DIV layer, the functionality breaks. This has been an issue with other scripts as well. How can this be addressed?

Thank you.

Answer №1

I have made some adjustments to your code in order for the image to shift to the left when the mouse moves too far to the right:

var posX = 0, posY = 0, offsetX = 0, offsetY = 0, viewportWidth;

function updateCursorPosition(e) { 
    posX = e.pageX; 
    posY = e.pageY; 
}

function updateCursorPositionDocAll(e) { 
    posX = event.clientX; 
    posY = event.clientY;
}

if (document.all) { 
    document.onmousemove = updateCursorPositionDocAll; 
} else { 
    document.onmousemove = updateCursorPosition; 
}

function assignPosition(el) {
    if (self.pageYOffset) {
        offsetX = self.pageXOffset;
        offsetY = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
        offsetX = document.documentElement.scrollLeft;
        offsetY = document.documentElement.scrollTop;
    } else if (document.body) {
        offsetX = document.body.scrollLeft;
        offsetY = document.body.scrollTop;
    }
    
    if (document.all) {
        posX += offsetX; 
        posY += offsetY;
    }
    
    var elementWidth = el.offsetWidth;
    
    if (posX + 10 + elementWidth > viewportWidth) { 
        el.style.left = (posX - 10 - elementWidth) + 'px'; 
    } else { 
        el.style.left = (posX + 10) + 'px'; 
    }
    
    el.style.top = (posY + 10) + 'px';
}

function hideContent(elementId) {
    if (elementId.length < 1) return;
    
    document.getElementById(elementId).style.display = 'none';
}

function showContent(elementId, imagePath) {
    viewportWidth = getViewportWidth();
    
    if (elementId.length < 1) return;
    
    var element = document.getElementById(elementId);
    
    assignPosition(element);
    
    element.style.display = 'block';
    document.getElementById(elementId).innerHTML = '<img src="' + imagePath + '" />';
}

function reverseContentDisplay(elementId) {
    if (elementId.length < 1) return;
    
    var element = document.getElementById(elementId);
    
    assignPosition(element);
    
    element.style.display = (element.style.display == 'none') ? 'block' : 'none';
}

function getViewportWidth() {
    if (self.innerWidth) return self.innerWidth;
    else if (document.documentElement && document.documentElement.clientWidth)
        return document.documentElement.clientWidth;
    else if (document.body) return document.body.clientWidth;
}

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

Possible solution to address the issue: xhr.js:178 encountered a 403 error when attempting to access https://www.googleapis.com/youtube/v3/search?q=Tesla

Encountering this console error: xhr.js:178 GET https://www.googleapis.com/youtube/v3/search?q=river 403 A specific component was designed to utilize the API at a later point: const KEY = "mykeyas23d2sdffa12sasd12dfasdfasdfasdf"; export default ...

Loop through the XML string inside a for loop using Javascript

Hey everyone, I'm having some trouble with looping through strings for XML inside a for loop. I've attempted the following code but the loop doesn't seem to be working: var data = [{"name": "Tom", age: "20"}, {& ...

What is the best method for circumventing an express middleware?

I am currently working on an express application that utilizes several express routes, such as server.get('*' , ... ) to handle common operations like authentication, validation, and more. These routes also add extra information to the respon ...

Tips for placing modal box in the exact desired position upon loading

I've been searching for a solution on how to dynamically calculate the position of each image loaded in a Twitter modal box and place the box underneath a custom toolbar element I have created. The situation is depicted in the image. The height of the ...

What is the process for recording information using a static method in TypeScript within a class?

For my school project, I'm struggling to retrieve the names from a class using a method. One class creates monsters and another extends it. abstract class genMonster { constructor( public id: string, public name: string, public weaknesse ...

determine variances between two Java script objects

I need help with comparing two JavaScript objects to find the differences. The code I am using in the function is not giving me the desired output. function compare() { var Json1 = [ { name: "ABC", value: "5" }, { name: "DEF", value: "85712264" ...

Looking for a powerful filtering menu similar to Excel or Kendo UI Grid in Datatables?

Is there a way to add Excel-like filtering to DataTables? It's surprising that such a widely used and advanced plugin doesn't have this feature already. If not, is there an easy way to implement it? Below are examples of advanced menu filters sim ...

Decoding JSON data in AngularJS

A json object has a key named lastLogin which holds a string value. I am attempting to display the names John and Blake. $scope._users = [{ "User": { "userid": "dummy", "lastlogin": "{\"employees\":[{\"first ...

What is the best way to update a canvas chart when the side menu is hidden?

I am facing an issue with the layout of my webpage, which includes a left side menu and a canvas chart. The left side menu occupies the first 155 pixels of the width, leaving the rest for the canvas chart set to a width of 100%. However, when I close the ...

What is the best way to link asynchronous methods in NodeJS NPM soap without relying on callbacks? Is it possible to leverage async/await

I have successfully utilized nodejs/javascript to call a series of soap webservice methods, however, I am currently using callbacks in my code. The code snippet looks like this: soap.createClient(wsdlUrl, function (err, soapClient) { console.log("soa ...

Exploring the effectiveness of Jest for testing HTTP GET requests

I am currently developing an API that uses a GET request on /api/flights/ to retrieve an array of Flights. All flights in the array have the same properties. I am looking for a way to verify if the flights list in my response.body matches an array of the s ...

What could be the reason why I am unable to load the ejs file?

https://i.stack.imgur.com/91bPg.png Issue: Unable to find the "index.ejs" view in the views directory ...

Having issues with ng-repeat not displaying any content

Let me describe the current situation I am facing: app.controller('ResourceController', function($scope, $sce){ var resourceData; $scope.data = ''; $scope.loadResources = function(){ $.get('con ...

Database not receiving input data from AngularJS form submission

Having some trouble saving form data to the database using angularjs. Not sure what I'm doing wrong. Here's my HTML form: <form id="challenge_form" class="row" > <input type="text" placeholder="Challenge Name" ng-model="ch ...

File Upload yields a result of 'undefined'

Currently, I am utilizing Express File Upload. When attempting to send a post request to it, the error-handler returns an error indicating that no files were found. Upon logging console.log(req.files), it shows as undefined, causing the error to be sent ba ...

Having trouble running a query in Flask with MySQL

Greetings! I am currently attempting to run a SQL query using Flask with a MySQL database. The query is expected to return JSON data managed by JQuery on the front end. The objective is to utilize a search bar to identify any matches within the database. W ...

Troubleshooting: jQuery addClass() function not functioning properly in conjunction with attr("href", something)

I am trying to implement a unique feature for a link using a Bootstrap button, where it only works on the second click. On the first click, the appearance of the link should change slightly. To achieve this, I am utilizing the .addClass(newClass), .removeC ...

How can I pass the data-attribute ID from JavaScript to PHP on the same index page using ajax?

I am struggling with the title for this section. Please feel free to modify it as needed. Introduction: I have been working on setting up a datatables.net library server-side table using JSON and PHP. Most of the work is done, but I am facing challenges w ...

How to properly convert JSON into a string within a nested object

Below is the JSON that I am passing and its result when logged in the console: boundary: Array(1) 0: points: Array(98) 0: {x: 117.5, y: 99} 1: Point {x: 116.5, y: 100} 2: Point {x: 116.5, y: 103} 3: Point {x: 114.5, y: 109} 4: Point {x: 113.5, y: 116} 5: P ...

When trying to target the checkbox value, the error "Object Expected"

My script successfully changes the value of a checkbox to toggle whether or not the user is in a specific Skype response group: var ie = WSH.CreateObject('InternetExplorer.Application'); url = "https://lyncfeg.DOMAIN.COM/RgsClients/Tab.a ...