jQuery drag very wide div horizontally - javascript

Hi I've got this wide div, that I'd like to be able to drag horizontally, for a metro style interface.
http://jsfiddle.net/hwvvu2rg/7/
var el_w = $('.draggable').outerWidth();
$('#guide').on("mousemove", function(e) {
if ($dragging) {
$('#guide').offset({
left: e.pageX - el_w / 2
});
}
Currently everytime you mousedown, it resets to the first position, how do I adjust the maths so that each time you drag it uses the current position, so you can drag it along?

You can capture the relative position on mousedown (such as e.pageX - (parseInt($(this).css('left')) || 0)), try this:
http://jsfiddle.net/hwvvu2rg/9/

Related

Get Div's new left position percentage on drag

I'm working on resizing a div on drag an updating it's left position accordingly.
The div starts in the center of the page using the following CSS style
left: `calc (50% + ${offsetX})`
where the values offsetX is initially 0. When a user clicks and drags on one of the resize handles the offsetX value will be updated according so that the div stays in the same posistion, but the width increases.
width: initialWidth + offsetX * 2
However, this only works when the div is still in the middle of the page. Once I drag the div somewhere else and try to resize it, it sort of jumps position because it's calculation is still based of the left position being at 50%. Is there any way I can get the new percentage left position of the div on drag so that I can do something like below
left: leftPercent === 0 ? `calc (50% + ${offsetX})` : `calc (${leftPercent}% + ${offsetX})`
You can calculate it using the element's left position and screen.width like this:
function getPercent(elementLeft) {
return elementLeft / screen.width * 100;
}

Client X/Y on Chrome (Android)

I wish to retrieve the exact X/Y coordinates where the user has pressed on the screen. The coordinates must be the same no matter what level of zoom or scroll is applied. I am using event.clientX and event.clientY to retrieve these coordinates and this behaves as expected. The code is basically as follows:
$("#canvas").touchstart(function(e){
e.preventDefault();
var Y_LIMIT = 100
if(e.clientY <= Y_LIMIT){
... do stuff
}
});
A textarea is present on the screen with a submit button to allow the user to enter text. The issue is after the tablet focuses in on the textarea and the user enters text the clientX and clientY coordinates permanently change. I wish for the values to stay the same regardless of this operation.
Is there any way to keep clientX and clientY consistent even after entering text into a textarea or input box ?
Despite the fact that there is still a question left about how clientX & clientY have changed(did they descrease or increase their values?)
If they descreased their values you could give this a try to take the absolute position of a parent HTML element(DIV?) in which your textarea is located into consideration:
Check out this answer that answers about how to get absolute position of a HTML element:
// get absolut position of an HTML element
function cumulativeOffset (element) {
var top = 0, left = 0;
do {
top += element.offsetTop || 0;
left += element.offsetLeft || 0;
element = element.offsetParent;
} while(element);
return {
top: top,
left: left
};
};
// event handler callback function to retrieve client position
function funcToGetClientCoords(evt){
var area = document.getElementById("parentDIVId");
var absoluteViewportPos = cumulativeOffset(area);
return {
x: evt.clientX + absoluteViewportPos.left,
y: evt.clientY + absoluteViewportPos.top
};
}
I did not prove this but it sounds to me as if clientX & clientY coords changed according to your relative screenview position and when you click onto a textarea you automatically zoom into this textarea and so clientX and clientY coords might be descreased.
Another try could be to remember the absolute position of your parent DIV at the beginning and when interacting with your textarea add this position to clientX/clientY positions.
Hope this helps.

Dragging of element goes wrong when the container is scrolled

In this Fiddle, I made the red container draggable. As you can see, this is working fine but when the green container (parent container) is scrolled a bit and then the red container is dragged, the dragging is not happening at correct position.
Can someone please tell me what could be the problem?
I tried e.pageX, e.clientX and e.offsetX but still couldn't able to fix this. (or maybe I missed something)
You need to add the scrolling top position to your shape. If you want your square stay on the correct position check that:
function repositionShape(e) {
$self = repositionStart.self;
$commentSection = repositionStart.commentSection;
var dy = $('.wrapper').scrollTop(); // Get wrapper scroll position
$self.css({
'left': e.clientX - repositionStart.offset.left,
'top': e.clientY - repositionStart.offset.top +dy // Add delta to your square position
});
}

Position tooltip above mouse when room in viewport, otherwise below mouse

I am creating a tooltip and am having some problems with positioning it.
The tooltip is set to position: absolute, and I have a handler for mouse events that modifies it's top and left CSS depending on the pageX and pageY.
Now, I know I can just set the top to pageY and left to pageX. That will make the tooltip pop up to the bottom-right. I'm trying to orient it where it pops up on the top-right when there is room, but if it would be out of the viewport on the Y-axis, drop to the bottom-right position again.
At the moment, I'm stuck trying to get the tooltip to show to the top-right of the mouse. I don't even know where to begin detecting if it would be in the viewport. Can anyone point me in the right direction?
$('p').on('mouseenter', function(e) {
$(tt).css('top', e.pageY - $(tt).css('height'));
$(tt).css('left', e.pageX);
$(tt).appendTo('body');
}).on('mousemove', function(e) {
$(tt).css('top', e.pageY - $(tt).css('height'));
$(tt).css('left', e.pageX);
}).on('mouseleave', function(e) {
$(tt).detach();
});
Example on JSFiddle
There are many different ways to handle tooltips, especially when using jQuery. This method probably would not have been my first choice. However, the following changes should work how you intended.
var tt = document.createElement('div');
tt.id = "tt";
$('p').on('mouseenter', function(e) {
var curPos = $( this ).offset().top - $( window ).scrollTop();
var inView = (curPos < 250) ? 0 : 250;
$(tt).css('top', e.pageY - inView);
$(tt).css('left', e.pageX);
$(tt).append($( this ).attr("data-myId"));
$(tt).appendTo('body');
}).on('mousemove', function(e) {
$(tt).css('top', e.pageY - $(tt).css('height'));
$(tt).css('left', e.pageX);
}).on('mouseleave', function(e) {
$(tt).empty($( this ).attr("data-myId"));
$(tt).detach();
});
Full changes in JSFiddle.
I am taking advantage of jQuery's offset() and scrollTop() methods to estimate the position of the current element within the viewable area of the document.
According to jQuery's API documentation, the .offset() method
allows us to retrieve the current position of an element relative to
the document. The documentation also states that the vertical
scroll position (.scrollTop()) is the same as the number of pixels that are hidden
from view above the scrollable area.
We use both of these methods to our advantage and subtract the number of pixels above the scrollable area from the current position of the element relative to the document. One important thing to note is that the offset method returns an object with the properties top and left.
var curPos = $( this ).offset().top - $( window ).scrollTop();
Since you had the #tt id set to a static 250px height, we can check if the current element position relative to the viewable portion of the window is less than 250. If it is, then we subtract nothing and let the tool tip sit below the mouse position. If it is greater than 250 then we subtract 250px and the tool tip will be above the current mouse position.
I am not sure how you were intending to pull in the content for the tool tips, but I also added $(tt).append($( this ).attr("data-myId")); to use the data-myId value as the tool tip content and $(tt).empty($( this ).attr("data-myId")); to clear it on mouseleave. I hope this helps!

How use JQuery/Javascript to scroll down a page when the cursor at the top or bottom edge of the screen?

Simple, I just would like to have it so when a user is dragging an item and they reach the very bottom or top of the viewport (10px or so), the page (about 3000px long) gently scrolls down or up, until they move their cursor (and thus the item being dragged) out of the region.
An item is an li tag which uses jquery to make the list items draggable. To be specific:
../jquery-ui-1.8.14.custom.min.js
http://code.jquery.com/jquery-1.6.2.min.js
I currently use window.scrollBy(x=0,y=3) to scroll the page and have the variables of:
e.pageY ... provides absolute Y-coordinates of cursor on page (not relative to screen)
$.scrollTop() ... provides offset from top of page (when scroll bar is all the way up, it is 0)
$.height()... provides the height of viewable area in the user's browser/viewport
body.offsetHeight ... height of the entire page
How can I achieve this and which event best accommodates this (currently its in mouseover)?
My ideas:
use a an if/else to check if it is in top region or bottom, scroll up if e.pageY is showing it is in the top, down if e.page& is in bottom, and then calling the $('li').mouseover() event to iterate through...
Use a do while loop... this has worked moderately well actually, but is hard to stop from scrolling to far. But I am not sure how to control the iterations....
My latest attempt:
('li').mouseover(function(e) {
totalHeight = document.body.offsetHeight;
cursor.y = e.pageY;
var papaWindow = window;
var $pxFromTop = $(papaWindow).scrollTop();
var $userScreenHeight = $(papaWindow).height();
var iterate = 0;
do {
papaWindow.scrollBy(0, 2);
iterate++;
console.log(cursor.y, $pxFromTop, $userScreenHeight);
}
while (iterate < 20);
});
Works pretty well now, user just needs to "jiggle" the mouse when dragging items sometimes to keep scrolling, but for scrolling just with mouse position its pretty solid. Here is what I finally ended up using:
$("li").mouseover(function(e) {
e = e || window.event; var cursor = { y: 0 }; cursor.y = e.pageY; //Cursor YPos
var papaWindow = parent.window;
var $pxFromTop = $(papaWindow).scrollTop();
var $userScreenHeight = $(papaWindow).height();
if (cursor.y > (($userScreenHeight + $pxFromTop) / 1.25)) {
if ($pxFromTop < ($userScreenHeight * 3.2)) {
papaWindow.scrollBy(0, ($userScreenHeight / 30));
}
}
else if (cursor.y < (($userScreenHeight + $pxFromTop) * .75)) {
papaWindow.scrollBy(0, -($userScreenHeight / 30));
}
}); //End mouseover()
This won't work as the event only fires while you're mouse is over the li.
('li').mouseover(function(e) { });
You need to be able to tell the position of the mouse relative to the viewport when an item is being dragged. When the users starts to drag an item attach an 'mousemove' event to the body and then in that check the mouse position and scroll when necessary.
$("body").on("mousemove", function(event) {
// Check mouse position - scroll if near bottom or top
});
Dont forget to remove your event when the user stops dragging.
$("body").off("mousemove", function(event) {
// Check mouse position - scroll if near bottom or top
});
This may not be exactly what you want, but it might help. It will auto-scroll when the mouse is over the 'border of the screen' (a user defined region). Say you have a 40px wide bar on the right of the screen, if the mouse reaches the first 1px, it will start scrolling. Each px you move into it, the speed will increase. It even has a nice easing animation.
http://www.smoothdivscroll.com/v1-2.htm
I get a weekly newsletter (email) from CodeProject, and it had some stuff that certainly looks like it will solve my problem... hopefully this can help others:
http://johnpolacek.github.com/scrollorama/ -- JQuery based and animates the scroll
https://github.com/IanLunn/jQuery-Parallax -- JQuery based, similar to above
http:// remysharp. com/2009/01/26/element-in-view-event-plugin/ -- JQuery, detects whether an element is currently in view of the user (super helpful for this issue!)
Also the site in #2 had some interesting code:
var windowHeight = $window.height();
var navHeight = $('#nav').height() / 2;
var windowCenter = (windowHeight / 2);
var newtop = windowCenter - navHeight;
//ToDo: Find a way to use these vars and my original ones to determine scroll regions

Categories

Resources