On the following page I have a popup that is supposed to show beside the image, depending on the window size the pop-up displays further/closer to the mouse. I don't understand what is wrong with the code, that makes the pop-up not display in the same proximity to the mouse?
http://www.hughgrice.com/test/
jQuery(document).mousemove(function (e) {
mouseX = e.pageX;
mouseY = e.pageY;
follow();
});
function follow(){
d = document.getElementById("thumbTT");
if(openToolTip){
d.style.display = "block";
d.style.left = mouseX+5 + "px";
d.style.top = mouseY-100 + "px";
}else{
d.style.display = "none";
}
}
http://www.hughgrice.com/test/
This should work:
var $elem = $( '#thumbTT' );
$( document ).on( 'mousemove', function ( e ) {
follow( e.pageX, e.pageY );
});
function follow ( x, y ) {
if( openToolTip ) {
$elem.css({ left: x + 5, top: y - 100 }).show();
} else {
$elem.hide();
}
}
I'm assuming that the #thumbTT element is static, so I'm caching the reference to it beforehand.
As your wrapper DIV is relative positioned that's why it is not positioned correctly. Either you have to remove the position:relative from your wrapper div or you have to write your mousemove function like
jQuery(document).mousemove(function (e) {
var offset = jQuery(this).css('offset');
mouseX = offset.left;
mouseY = offset.top;
follow();
});
maybe you have to adjust your code
Related
I am trying to have a div in a container which when the user clicks and drags somewhere in the document area, the .room element pans around inside the .viewport element by holding down the middle click button.
Here is the issue: (Hold right click for this one, middle click didn't work for some reason)
http://jsfiddle.net/JeZj5/2/
JS
var mouseX = 0;
var mouseY = 0;
var scale = 1.0;
$(document).mousemove(function (e) {
var offset = $('.room').offset();
//relative mouse x,y
mouseX = parseFloat((e.pageX - offset.left) / scale, 2);
mouseY = parseFloat((e.pageY - offset.top) / scale, 2);
//absolute mouse x,y
mouseXRaw = e.pageX;
mouseYRaw = e.pageY;
$(".room").html(mouseX + ', ' + mouseY + '<br />Right click document and pan');
switch (e.which) {
case 3:
$('.room').css({
left: mouseX,
top: mouseY
});
break;
}
return true;
});
$(document).on('contextmenu', function () {
return false;
});
This should be more along the lines of what you're looking for. Key change:
delta.x = e.pageX - drag.x;
delta.y = e.pageY - drag.y;
Using the delta to change the position. The .room's position should be moving with respect to it's current location, minus the mouse drag position (not the other way around).
http://jsfiddle.net/X2PZP/3/
This question already has answers here:
Moveable/draggable <div>
(9 answers)
Closed 5 years ago.
I want to create a movable/draggable div in native javascript without using jquery and libraries. Is there a tutorial or anythign?
OK, here's my personal code that I use for lightweight deployments (projects where using a library is either not allowed or overkill for some reason). First thing first, I always use this convenience function so that I can pass either an id or the actual dom element:
function get (el) {
if (typeof el == 'string') return document.getElementById(el);
return el;
}
As a bonus, get() is shorter to type than document.getElementById() and my code ends up shorter.
Second realize that what most libraries are doing is cross-browser compatibility. If all browsers behave the same the code is fairly trivial. So lets write some cross-browser functions to get mouse position:
function mouseX (e) {
if (e.pageX) {
return e.pageX;
}
if (e.clientX) {
return e.clientX + (document.documentElement.scrollLeft ?
document.documentElement.scrollLeft :
document.body.scrollLeft);
}
return null;
}
function mouseY (e) {
if (e.pageY) {
return e.pageY;
}
if (e.clientY) {
return e.clientY + (document.documentElement.scrollTop ?
document.documentElement.scrollTop :
document.body.scrollTop);
}
return null;
}
OK, the two functions above are identical. There're certainly better ways to write them but I'm keeping it (relatively) simple for now.
Now we can write the drag and drop code. The thing I like about this code is that everything's captured in a single closure so there are no global variables or helper functions littering the browser. Also, the code separates the drag handle from the object being dragged. This is useful for creating dialog boxes etc. But if not needed, you can always assign them the same object. Anyway, here's the code:
function dragable (clickEl,dragEl) {
var p = get(clickEl);
var t = get(dragEl);
var drag = false;
offsetX = 0;
offsetY = 0;
var mousemoveTemp = null;
if (t) {
var move = function (x,y) {
t.style.left = (parseInt(t.style.left)+x) + "px";
t.style.top = (parseInt(t.style.top) +y) + "px";
}
var mouseMoveHandler = function (e) {
e = e || window.event;
if(!drag){return true};
var x = mouseX(e);
var y = mouseY(e);
if (x != offsetX || y != offsetY) {
move(x-offsetX,y-offsetY);
offsetX = x;
offsetY = y;
}
return false;
}
var start_drag = function (e) {
e = e || window.event;
offsetX=mouseX(e);
offsetY=mouseY(e);
drag=true; // basically we're using this to detect dragging
// save any previous mousemove event handler:
if (document.body.onmousemove) {
mousemoveTemp = document.body.onmousemove;
}
document.body.onmousemove = mouseMoveHandler;
return false;
}
var stop_drag = function () {
drag=false;
// restore previous mousemove event handler if necessary:
if (mousemoveTemp) {
document.body.onmousemove = mousemoveTemp;
mousemoveTemp = null;
}
return false;
}
p.onmousedown = start_drag;
p.onmouseup = stop_drag;
}
}
There is a reason for the slightly convoluted offsetX/offsetY calculations. If you notice, it's just taking the difference between mouse positions and adding them back to the position of the div being dragged. Why not just use the mouse positions? Well, if you do that the div will jump to the mouse pointer when you click on it. Which is a behavior I did not want.
You can try this
HTML
<div id="one" style="height:50px; width:50px; border:1px solid #ccc; background:red;">
</div>
Js Script for draggable div
window.onload = function(){
draggable('one');
};
var dragObj = null;
function draggable(id)
{
var obj = document.getElementById(id);
obj.style.position = "absolute";
obj.onmousedown = function(){
dragObj = obj;
}
}
document.onmouseup = function(e){
dragObj = null;
};
document.onmousemove = function(e){
var x = e.pageX;
var y = e.pageY;
if(dragObj == null)
return;
dragObj.style.left = x +"px";
dragObj.style.top= y +"px";
};
Check this Demo
This code corrects the position of the mouse (so the dragged object doesn't jump when you start dragging) and works with touch screens/phones as well
var dragObj = null; //object to be moved
var xOffset = 0; //used to prevent dragged object jumping to mouse location
var yOffset = 0;
window.onload = function()
{
document.getElementById("menuBar").addEventListener("mousedown", startDrag, true);
document.getElementById("menuBar").addEventListener("touchstart", startDrag, true);
document.onmouseup = stopDrag;
document.ontouchend = stopDrag;
}
function startDrag(e)
/*sets offset parameters and starts listening for mouse-move*/
{
e.preventDefault();
e.stopPropagation();
dragObj = e.target;
dragObj.style.position = "absolute";
var rect = dragObj.getBoundingClientRect();
if(e.type=="mousedown")
{
xOffset = e.clientX - rect.left; //clientX and getBoundingClientRect() both use viewable area adjusted when scrolling aka 'viewport'
yOffset = e.clientY - rect.top;
window.addEventListener('mousemove', dragObject, true);
}
else if(e.type=="touchstart")
{
xOffset = e.targetTouches[0].clientX - rect.left; //clientX and getBoundingClientRect() both use viewable area adjusted when scrolling aka 'viewport'
yOffset = e.targetTouches[0].clientY - rect.top;
window.addEventListener('touchmove', dragObject, true);
}
}
function dragObject(e)
/*Drag object*/
{
e.preventDefault();
e.stopPropagation();
if(dragObj == null) return; // if there is no object being dragged then do nothing
else if(e.type=="mousemove")
{
dragObj.style.left = e.clientX-xOffset +"px"; // adjust location of dragged object so doesn't jump to mouse position
dragObj.style.top = e.clientY-yOffset +"px";
}
else if(e.type=="touchmove")
{
dragObj.style.left = e.targetTouches[0].clientX-xOffset +"px"; // adjust location of dragged object so doesn't jump to mouse position
dragObj.style.top = e.targetTouches[0].clientY-yOffset +"px";
}
}
function stopDrag(e)
/*End dragging*/
{
if(dragObj)
{
dragObj = null;
window.removeEventListener('mousemove', dragObject, true);
window.removeEventListener('touchmove', dragObject, true);
}
}
div{height:400px; width:400px; border:1px solid #ccc; background:blue; cursor: pointer;}
<div id="menuBar" >A</div>
<div draggable=true ondragstart="event.dataTransfer.setData('text/plain', '12345')">
drag me
</div>
<div ondragover="return false;" ondrop="this.innerHTML=event.dataTransfer.getData('text/plain')">
drop on me
</div>
I have the following bit of code which is responsible for displaying a tooltip. I am unhappy with this code for two reasons:
I use pageXOffset and pageYOffset 'magic numbers' to correct the visual state per-browser.
The dialog window must remain stationary for the numbers to be correct.
I have tried binding to the dialog window's mousemove event instead of the document. The results were identical to my current implementation which binds to document's mousemove.
var shouldDisplay = false;
$(document).mousemove(AdjustToolTipPosition);
function DisplayTooltip(tooltip_text) {
shouldDisplay = (tooltip_text != "") ? true : false;
if (shouldDisplay) {
$('#CustomTooltip').html(tooltip_text);
$('#CustomTooltip').show();
}
else {
//Sometimes the tooltip hasn't finished fading in before we ask to hide it. This causes it to hide, then fade back in.
$('#CustomTooltip').hide();
}
}
function AdjustToolTipPosition(e) {
if (shouldDisplay) {
//msie e.page event should be standardizes, but seems to go awry when working inside of a modal window.
var pageYOffset = $.browser.msie ? 260 : 572; //-314
var pageXOffset = $.browser.msie ? 474 : 160; //+314
$('#CustomTooltip').css('top', e.pageY - pageYOffset + 'px');
var offsetLeft = e.pageX - pageXOffset;
var isOutsideViewport = $("#HistoricalChartDialog").width() - $("#CustomTooltip").width() - offsetLeft < 0;
//Prevent the tooltip from going off the screen by changing the offset when it would go off screen.
if (isOutsideViewport) {
offsetLeft = $("#HistoricalChartDialog").width() - $("#CustomTooltip").width();
}
$('#CustomTooltip').css('left', offsetLeft + 'px');
}
}
// Initialize the Historical Chart dialog.
$('#HistoricalChartDialog').dialog({
autoOpen: false,
buttons: {
'Close': function() {
$(this).dialog('close');
}
},
hide: 'fold',
modal: true,
draggable: false,
resizable: false,
position: 'center',
title: 'Historical Charts',
width: 700,
height: 475
});
I provide the jQuery dialog initializer just for the sake of it. The tooltip only displays inside of this dialog window -- but the coordinates are for the entire page. Is it possible to retrieve coordinates relative to the dialog window so that I can leverage the fact that jQuery's mousemove standardizes coordinates with the pageX and pageY properties?
EDIT solution:
//Seperate file because the offsets are different for the image under MVC.
var shouldDisplay = false;
$("#HistoricalChartDialog").mousemove(AdjustToolTipPosition);
function DisplayTooltip(tooltip_text) {
shouldDisplay = (tooltip_text != "") ? true : false;
if (shouldDisplay) {
$('#CustomTooltip').html(tooltip_text);
$('#CustomTooltip').show();
}
else {
//Sometimes the tooltip hasn't finished fading in before we ask to hide it. This causes it to hide, then fade back in.
$('#CustomTooltip').hide();
}
}
function AdjustToolTipPosition(e) {
if (shouldDisplay) {
var xPos = e.pageX - $(this).closest('.ui-dialog').offset().left + 15;
var widthDifference = $(this).width() - $("#CustomTooltip").width();
//Prevent the tooltip from going off the screen by changing the offset when it would go off screen.
xPos = (widthDifference - xPos < 0) ? widthDifference : xPos;
$('#CustomTooltip').css('left', xPos + 'px');
var yPos = e.pageY - $(this).closest('.ui-dialog').offset().top - 10;
$('#CustomTooltip').css('top', yPos + 'px');
}
}
To get the position of the mouse relative to a specific div, not the viewport, you take the eventX/Y and subtract the left/top position of the div:
$("#example").mousemove(function(e) {
var xPos = e.pageX - $(this).position().left;
var yPos = e.pageY - $(this).position().top;
$("#pos").text("x: " + xPos + " / y: " + yPos);
});
Example fiddle
Given your example, this should work. You may need to look at your isOutsideViewport logic though.
function AdjustToolTipPosition(e) {
if (shouldDisplay) {
var xPos = e.pageX - $(this).position().left;
var yPos = e.pageY - $(this).position().top;
var isOutsideViewport = $("#HistoricalChartDialog").width() - $("#CustomTooltip").width() - xPos < 0;
if (isOutsideViewport) {
offsetLeft = $("#HistoricalChartDialog").width() - $("#CustomTooltip").width();
}
$('#CustomTooltip').css({
'top': yPos + 'px',
'left': xPos + 'px'
});
}
}
I have the following event handler for my html element
jQuery("#seek-bar").click(function(e){
var x = e.pageX - e.target.offsetLeft;
alert(x);
});
I need to find the position of the mouse on the #seek-bar at the time of clicking. I would have thought the above code should work, but it gives incorrect result
Are you trying to get the position of mouse pointer relative to element ( or ) simply the mouse pointer location
Try this Demo : http://jsfiddle.net/AMsK9/
Edit :
1) event.pageX, event.pageY gives you the mouse position relative document !
Ref : http://api.jquery.com/event.pageX/
http://api.jquery.com/event.pageY/
2) offset() : It gives the offset position of an element
Ref : http://api.jquery.com/offset/
3) position() : It gives you the relative Position of an element i.e.,
consider an element is embedded inside another element
example :
<div id="imParent">
<div id="imchild" />
</div>
Ref : http://api.jquery.com/position/
HTML
<body>
<div id="A" style="left:100px;"> Default <br /> mouse<br/>position </div>
<div id="B" style="left:300px;"> offset() <br /> mouse<br/>position </div>
<div id="C" style="left:500px;"> position() <br /> mouse<br/>position </div>
</body>
JavaScript
$(document).ready(function (e) {
$('#A').click(function (e) { //Default mouse Position
alert(e.pageX + ' , ' + e.pageY);
});
$('#B').click(function (e) { //Offset mouse Position
var posX = $(this).offset().left,
posY = $(this).offset().top;
alert((e.pageX - posX) + ' , ' + (e.pageY - posY));
});
$('#C').click(function (e) { //Relative ( to its parent) mouse position
var posX = $(this).position().left,
posY = $(this).position().top;
alert((e.pageX - posX) + ' , ' + (e.pageY - posY));
});
});
$('#something').click(function (e){
var elm = $(this);
var xPos = e.pageX - elm.offset().left;
var yPos = e.pageY - elm.offset().top;
console.log(xPos, yPos);
});
Try this:
jQuery(document).ready(function(){
$("#special").click(function(e){
$('#status2').html(e.pageX +', '+ e.pageY);
});
})
Here you can find more info with DEMO
In percentage :
$('.your-class').click(function (e){
var $this = $(this); // or use $(e.target) in some cases;
var offset = $this.offset();
var width = $this.width();
var height = $this.height();
var posX = offset.left;
var posY = offset.top;
var x = e.pageX-posX;
x = parseInt(x/width*100,10);
x = x<0?0:x;
x = x>100?100:x;
var y = e.pageY-posY;
y = parseInt(y/height*100,10);
y = y<0?0:y;
y = y>100?100:y;
console.log(x+'% '+y+'%');
});
If MouseEvent.offsetX is supported by your browser (all major browsers actually support it), The jQuery Event object will contain this property.
The MouseEvent.offsetX read-only property provides the offset in the X coordinate of the mouse pointer between that event and the padding edge of the target node.
$("#seek-bar").click(function(event) {
var x = event.offsetX
alert(x);
});
see here enter link description here
html
<body>
<p>This is a paragraph.</p>
<div id="myPosition">
</div>
</body>
css
#myPosition{
background-color:red;
height:200px;
width:200px;
}
jquery
$(document).ready(function(){
$("#myPosition").click(function(e){
var elm = $(this);
var xPos = e.pageX - elm.offset().left;
var yPos = e.pageY - elm.offset().top;
alert("X position: " + xPos + ", Y position: " + yPos);
});
});
This question already has answers here:
How to get mouse position in jQuery without mouse-events?
(7 answers)
Closed 3 years ago.
In Javascript, within the Javascript event handler for onMouseMove how do I get the mouse position in x, y coordinates relative to the top of the page?
if you can use jQuery, then this will help:
<div id="divA" style="width:100px;height:100px;clear:both;"></div>
<span></span><span></span>
<script>
$("#divA").mousemove(function(e){
var pageCoords = "( " + e.pageX + ", " + e.pageY + " )";
var clientCoords = "( " + e.clientX + ", " + e.clientY + " )";
$("span:first").text("( e.pageX, e.pageY ) - " + pageCoords);
$("span:last").text("( e.clientX, e.clientY ) - " + clientCoords);
});
</script>
here is pure javascript only example:
var tempX = 0;
var tempY = 0;
function getMouseXY(e) {
if (IE) { // grab the x-y pos.s if browser is IE
tempX = event.clientX + document.body.scrollLeft;
tempY = event.clientY + document.body.scrollTop;
}
else { // grab the x-y pos.s if browser is NS
tempX = e.pageX;
tempY = e.pageY;
}
if (tempX < 0){tempX = 0;}
if (tempY < 0){tempY = 0;}
document.Show.MouseX.value = tempX;//MouseX is textbox
document.Show.MouseY.value = tempY;//MouseY is textbox
return true;
}
This is tried and works in all browsers:
function getMousePos(e) {
return {x:e.clientX,y:e.clientY};
}
Now you can use it in an event like this:
document.onmousemove=function(e) {
var mousecoords = getMousePos(e);
alert(mousecoords.x);alert(mousecoords.y);
};
NOTE: The above function will return the mouse co-ordinates relative to the viewport, which is not affected by scroll. If you want to get co-ordinates including scroll, then use the below function.
function getMousePos(e) {
return {
x: e.clientX + document.body.scrollLeft,
y: e.clientY + document.body.scrollTop
};
}
It might be a bit overkill to use d3.js just for finding mouse coordinates, but they have a very useful function called d3.mouse(*container*). Below is an example of doing what you want to do:
var coordinates = [0,0];
d3.select('html') // Selects the 'html' element
.on('mousemove', function()
{
coordinates = d3.mouse(this); // Gets the mouse coordinates with respect to
// the top of the page (because I selected
// 'html')
});
In the above case, the x-coordinate would be coordinates[0], and the y-coordinate would be coordinates[1]. This is extremely handy, because you can get the mouse coordinates with respect to any container you want to by exchanging 'html' with the tag (e.g. 'body'), class name (e.g. '.class_name'), or id (e.g. '#element_id').
Especially with mousemove events, that fire fast and furious, its good to pare down the handlers before you use them-
var whereAt= (function(){
if(window.pageXOffset!= undefined){
return function(ev){
return [ev.clientX+window.pageXOffset,
ev.clientY+window.pageYOffset];
}
}
else return function(){
var ev= window.event,
d= document.documentElement, b= document.body;
return [ev.clientX+d.scrollLeft+ b.scrollLeft,
ev.clientY+d.scrollTop+ b.scrollTop];
}
})()
document.ondblclick=function(e){alert(whereAt(e))};