I have been trying for a while now to get a simple pan of a div to work, I however can not seem to get it to 100%. It partially works with bugs.
$("#view_point").mousedown(function(e) {
start_x = e.pageX;
start_y = e.pageY;
e.preventDefault()
//On Click set start x and y vars
}).mousemove(function(e) {
temp_x = e.pageX;
temp_y = e.pageY;
e.preventDefault();
}).mouseup(function(e) {
temp_x = Math.abs(temp_x - start_x);
temp_x = Math.abs(temp_y - start_y);
console.log(temp_x + " - " + temp_y);
//Animate the map
$("#tiles").animate({
marginTop: '-' + temp_x,
marginLeft: '-' + temp_y
}, 50);
});
How do I go about making a pan script that will pan inside a div that has its overflow property set to hidden.
Related
I have a selection on a canvas, that I can drag and resize when it´s there.
I also can make it visible when I drag on the empty canvas.
But how do I make it visible and instantly have the bottom-right corner "in my hand" (for resizing); i.e. can I pass the drag event from the canvas to a resize event on the selection?
Is there a way with jQuery or do I have to make my own?
<div id="canvas" style="position:relative;width:500px;height:500px"
draggable="true" onDragStart="initSelection(event)">
<div id="selection" style="border:1px dashed gray;position:absolute;display:none"></div>
</div>
$('#selection').draggable({containment:'parent'}).resizable({containment:'parent'});
function initSelection(e){
if ('none'==$('#selection').css('display'))
{
var q=$('#canvas').offset();
$('#selection')
.css('left', e.clientX-q.left)
.css('top', e.clientY-q.top)
.css('width',10).css('height',10)
.css('display','block')
;
}
}
I think I see what you're trying to do.
Testing here: jsfiddle.net/Twisty/vkLjn0gL
I think you need to take one route or the other, not both at once.
resize the div with CSS based on the mousedown / mouseup events and
mouse x and y.
make it resizable up front and enable/start the resize
event tied to the mousemove until done and then make it draggable
I got this far when you posted that you found an answer: https://jsfiddle.net/Twisty/vkLjn0gL/5/
$(function() {
$("#canvas").on("dragstart", initSelection);
$("#canvas").on("mousemove", resize);
$("#canvas").on("mouseup", function() {
allowResize = false;
});
var allowResize = false;
/*
$('#selection').draggable({
containment: 'parent'
}).resizable({
containment: 'parent'
});
*/
function initSelection(e) {
if ('none' == $('#selection').css('display')) {
var q = $('#canvas').offset();
$('#selection')
.css('left', e.clientX - q.left)
.css('top', e.clientY - q.top)
.css('width', '10px').css('height', '10px')
.css('display', 'block');
allowResize = true;
}
}
function resize(e) {
if (allowResize) {
//console.log("MouseMove: ", e);
var w = $("#selection").width(),
h = $("#selection").height(),
q = $("#canvas").offset(),
px = 0,
py = 0;
px = e.clientX - q.left;
py = e.clientY - q.top;
console.log("Width: ", (w + px), " Height: ", (h + py));
$("#selection").css({
width: (w + px) + "px",
height: (h + py) + "px"
});
}
}
});
Update 1
Few fixes to mouse tracking:
https://jsfiddle.net/Twisty/vkLjn0gL/6/
function resize(e) {
if (allowResize) {
//console.log("MouseMove: ", e);
$("#canRes").html(allowResize);
$("#cx").html(e.clientX - $("#canvas").offset().left);
$("#cy").html(e.clientY - $("#canvas").offset().top);
$("#ox").html($("#selection").width());
$("#oy").html($("#selection").height());
var w = $("#selection").width(),
h = $("#selection").height(),
q = $("#canvas").offset(),
o = $("#selection").position();
px = 0,
py = 0;
if (w > $("#canvas").width() + q.left) {
return false;
}
if (h > $("#canvas").height() + q.top) {
return false;
}
px = e.clientX - q.left - o.left;
py = e.clientY - q.top - o.top;
$("#selection").css({
width: px + "px",
height: py + "px"
});
}
}
Update 2
I think this will do all that you wanted if you're still looking: https://jsfiddle.net/Twisty/vkLjn0gL/7/
Updated to selection after mouseup
$("#canvas").on("mouseup", function() {
allowResize = false;
$("#canRes").html(allowResize);
$("#selection").draggable({
containment: 'parent'
})
.resizable({
containment: 'parent'
});
});
Update 3
Added the drag handle on initial sizing: https://jsfiddle.net/Twisty/vkLjn0gL/10/
How can I make the other images also follow the mouse? Not all at the same time, but when I click on the selected image.
How can I calculate the distance where the mouse moved when I click on the image?
See link below.
HTML:
<div id="squarelocation"></div>
<div class="square 1">1</div>
<div class="square 2">2</div>
<div class="square 3">3</div>
Jquery:
$(document).ready(function () {
var i = true;
$(document).on('click', function () {
$(this)[i ? 'on' : 'off']('mousemove', follow);
i = !i;
});
function follow(e) {
var xPos = e.pageX;
var yPos = e.pageY;
$("#squarelocation").html("The square is at: " + xPos + ", " + yPos + "pixels");
$(".2").offset({
left: e.pageX,
top: e.pageY
});
}
});
I suggest you to bind a click event to the square class like this:
var clickedImage;
$('.square').click(function (e){
initialX = e.pageX;
initialY = e.pageY;
clickedImage = this;
});
and assign the context to a variable, so that you can refer to it whenever you needed. And then in your code, refer to that context instead of the hardcoded '.2':
$(clickedImage).offset({
left: e.pageX,
top: e.pageY
});
This way, the image clicked will be referred to, instead of just '2' following the mouse all the time.
Same for calculating the distance between the clicked origin and the current position, you can save the original spot on clicking the image:
var initialX;
var initialY;
$('.square').click(function (e){
initialX = e.pageX;
initialY = e.pageY;
clickedImage = this;
});
and do the calculation in the 'follow' function, of course how the calculation should be is up to you, but here is an example:
var distanceX = xPos - initialX;
var distanceY = yPos - initialY;
$("#squarelocation").html("The square is at: " + xPos + ", " + yPos + "pixels");
$('#squaredistance').html("Distance from origin: " + distanceX + ", " + distanceY);
Hope this help. jsfiddle: http://jsfiddle.net/FW9jV/1/
You could add an 'active' class for the active square. I added an example.
The active square will always be moving until you click to deactivate it.
http://jsfiddle.net/fG6kr/1/
$(document).ready(function () {
var i = true;
$('.square').on('click', function () {
if( $(this).hasClass("active"))
{
$(this).removeClass("active");
$(document).off('mousemove');
}
else
{
$(this).addClass("active");
$(document).on('mousemove', follow);
}
});
function follow(e) {
var xPos = e.pageX;
var yPos = e.pageY;
$("#squarelocation").html("The square is at: " + xPos + ", " + yPos + "pixels");
$('.active').offset({
left: e.pageX,
top: e.pageY
});
}
});
demo
$(function() {
$('.square').click(function(){
$(this).toggleClass('sel');
});
$(document).on('mousemove', function(e){
$(".sel").offset({left: e.pageX+10, top: e.pageY+10});
});
});
I wrote this simple code to print a small dot on the location where I clicked with the mouse pointer:-
$(document).ready(function(){
$('#pane').click(function(e){
var pixel = $('<div />')
.addClass('pixel')
.css({
top: e.clientY,
left: e.clientX
});
$('#pane').append(pixel)
});
});
See this fiddle I created. When I click anywhere inside the rectangle, a small dot is printed in that location. But the problem is that dot is not printed where the mouse pointer's tip was. See the below image to see what I meant:-
I tried in both Firefox and Chrome.
Your code is working correctly,
Zoom your page and check,
i have changed pixel height and width for better understanding from 2px to 3px.
and drawing from e.clientX -1 and e.clientY -1 position so it looks exactly center.
You can find Fiddle
The most examples I've found don't work if there are a scrolled page... I used this algorythm in order to get the position:
var getOffsets = function($event){
var p = {};
var body = "search the document for the body element";
p.x = body.offsetLeft;
p.y = body.offsetTop;
while (body.offsetParent) {
p.x = p.x + body.offsetParent.offsetLeft;
p.y = p.y + body.offsetParent.offsetTop;
if (body == document.getElementsByTagName("body")[0]) {
break;
}
else {
body = body.offsetParent;
}
}
return p;
}
However, after that you have to consider also other elements, im my case:
var GetExactClickPosition = function($event){
var tr = $($event.target);
if ($event.target.localName != 'tr'){
tr = $($event.target).closest('tr');
}
var listDiv = $($event.target).closest('div');
var p = getOffsets($event);
var container = $('#mailingListExcludeMenuContainer');
container.css({
top: p.y - listDiv.scrollTop() - tr.height() - container.height() + $event.offsetY + "px",
left: p.x + $event.offsetX + "px"
});
container.show();
};
I have a list with scroller inside the main scroller of the page...
I used it in order to show a little menu at the position of the mouse click.
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'
});
}
}
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))};