how to animate following the mouse in jquery - javascript

OK, this works perfectly fine for following my mouse.
//
$(document).mousemove(function(e){
$("#follower").css({
'top': e.pageY + 'px';
'left': e.pageX + 'px';
});
});
//
And this works great for animating the mouse to a clicked point
//
$(document).click(function(e){
$("#follower").animate({
top: e.pageY + 'px';
left: e.pageX + 'px';
}, 800);
});
//
But I personally feel that logically this SHOULD work! Coming from my point of view as the webscripter. Amd then my question is, how can I make this work. I want the #follower to try and follow my mouse with a dynamic kind of lagging behind feel.
//
$(document).mousemove(function(e){
$("#follower").animate({
top: e.pageY + 'px';
left: e.pageX + 'px';
}, 800);
});
//

How about using setInterval and an equation called zeno's paradox:
http://jsfiddle.net/88526/1/
That's the way I usually do it.
As requested, I've included the code in this answer. Given a div with absolute positioning:
CSS:
#follower{
position : absolute;
background-color : red;
color : white;
padding : 10px;
}
HTML:
<div id="follower">Move your mouse</div>
JS w/jQuery:
var mouseX = 0, mouseY = 0;
$(document).mousemove(function(e){
mouseX = e.pageX;
mouseY = e.pageY;
});
// cache the selector
var follower = $("#follower");
var xp = 0, yp = 0;
var loop = setInterval(function(){
// change 12 to alter damping, higher is slower
xp += (mouseX - xp) / 12;
yp += (mouseY - yp) / 12;
follower.css({left:xp, top:yp});
}, 30);

Related

Positioning div left/right or top/bottom of a mouse click with CSS

I need a popup to open from a mouse click's position. From a usability view, when the click's happen near the edges of window, I'm adjusting the position[to the right/ left of click & top/bottom of the click] of popup in JS as below:
function myfunc(e) {
let ele = document.getElementById('my-dialog');
ele.style["left"] =
(window.innerWidth - e.pageX) < ele.offsetWidth ? e.pageX - ele.offsetWidth : e.pageX;
ele.style["top"] =
(window.innerHeight - e.pageY) < ele.offsetHeight ? e.pageY - ele.offsetHeight : e.pageY; }
Is there a way this can be achieved using just CSS(or is there a better JS solution to the problem.)
Minimal working code example here.
See a working demo: https://jsfiddle.net/drumperl/ce532rnf/
To get this working, I changed the left and top style settings to add 'px'. According to the spec, a length setting requires a relative or absolute unit of measurement like 'px', '%' or 'em'.
https://developer.mozilla.org/en-US/docs/Web/CSS/length
function myfunc(e) {
let ele = document.getElementById('my-dialog');
var newLeft = (window.innerWidth - e.pageX) < ele.offsetWidth ? e.pageX - ele.offsetWidth : e.pageX;
ele.style.left = newLeft + 'px';
var newTop = (window.innerHeight - e.pageY) < ele.offsetHeight ? e.pageY - ele.offsetHeight : e.pageY;
ele.style.top = newTop + 'px';
}
document.onclick = myfunc;
Hope this helps.

Click not registering on Image element

I'm trying to get a click to register on my image tag to get the coordinates of the image click to position an svg element on top of it. As far as I understand, the way I have my code should account for bubbling events, but I'm not 100% certain. Can someone help me understand what I'm doing wrong, information I might be missing from it? As of now, nothing runs.
$(".playing-field").on("click", "#picture", function(e) {
var offset = $("#picture").offset();
var relativeX = (e.pageX - offset.left);
var relativeY = (e.pageY - offset.top);
console.log(relativeX, relativeY);
});
I forgot to add HTML before...
<div class="playing-field">
<img id="picture" src="assets/images/image.jpg">
<svg class="speechbubbles" width="100%" height="100%" preserveAspectRatio="xMinYMin meet">
</div>
I tried the code in Jsfiddle without my CSS, and it works, but when I do add the CSS, it doesn't. I'm not that familiar with CSS rules, so can someone tell me why it would interfere with the clicking of the image?
.playing-field {
position: relative;
height: 500px;
width: 100%;
}
#picture{
position: absolute;
}
.speechbubbles{
position: absolute;
}
You code runs very well.
Try This https://jsfiddle.net/2bm4zjdz/1
$(".playing-field").on("click", "#picture", function(e) {
var offset = $("#picture").offset();
var relativeX = (e.pageX - offset.left);
var relativeY = (e.pageY - offset.top);
alert( 'x : ' + relativeX + ' y :' + relativeY);
});
Looking around it seems that offset doesn't work in chrome so you will need to use position like so
$(function () {
$('#picture').click(function (e) {
var offset = $(this).position();
var relativeX = (e.pageX - offset.left);
var relativeY = (e.pageY - offset.top);
alert('x :' + relativeX + ' y :' + relativeY);;
});
});

Placing cursor in the center of a child div - mousemove event

I have div that can be placed anywhere inside another div. I am able to do this with jquery mousemove event. However it is not quite working. I am trying to get the mouse cursor to be in the center of the moving div. I set these css attributes inline with jquery 'top': relY + 30,'left': relX + 10 but no luck. As mention I am trying to get the cursor in the middle of the div. The user can only place the moving inside the parent div called middle-side empty. JSFIDDLE
I am trying to accomplish something similar to this: http://jsfiddle.net/Lqebpaov/
Jquery:
$('#button').click(function (e) {
$('<div />', {
class: 'draggable ui-widget-content',
text: $('textarea').val(),
appendTo: '.middle-side',
draggable: {
containment: 'parent'
}
}).addClass('placement');
$('.middle-side').parent().mousemove(function(e){
var offset = $(this).offset();
var relX = e.pageX - offset.left;
var relY = e.pageY - offset.top;
$('.placement').css({'top': relY + 30,'left': relX + 10, 'position': 'absolute'});
})
});
$('.middle-side').on('click', function(e){
var offset = $(this).offset();
var relX = e.pageX - offset.left;
var relY = e.pageY - offset.top;
$('.placement').css({'top': relY,'left': relX, 'position': 'absolute' });
$(this).off("mousemove").find('.placement').removeClass('placement')
});
HTML
<div>
<div class="middle-side empty"></div>
</div>
This was a fun question. I updated a lot of your Javascript, and set up my own JSFIDDLE.
With this setup you should be able to resize the boxes to any height/width combination and it will work as expected. You can check out the JSFIDDLE link, but here is the updated Javascript also:
$('#button').click(function (e) {
$('<div />', {
class: 'draggable ui-widget-content',
text: $('textarea').val(),
appendTo: '.middle-side',
draggable: {
containment: 'parent'
}
}).addClass('placement');
$('.middle-side').parent().mousemove(function(e){
var offset = $(this).offset(),
relX = e.pageX,
relY = e.pageY,
$dvPlacement = $('.placement'),
pWidth = $dvPlacement.outerWidth(),
pHeight = $dvPlacement.outerHeight(),
$dvOutBox = $('.middle-side'),
oWidth = $dvOutBox.outerWidth(),
oHeight = $dvOutBox.outerHeight(),
centerY = relY - pHeight / 2,
centerX = relX - pWidth / 2,
topBorder = $dvOutBox.offset().top,
bottomBorder = $dvOutBox.offset().top + oHeight,
leftBorder = $dvOutBox.offset().left,
rightBorder = $dvOutBox.offset().left + oWidth;
$dvPlacement.css({'top': centerY + pHeight > bottomBorder ? bottomBorder - pHeight :
centerY < topBorder ? topBorder :
centerY,
'left': centerX + pWidth > rightBorder ? rightBorder - pWidth :
centerX < leftBorder ? leftBorder :
centerX,
'position': 'absolute'
});
})
});
$('.middle-side').on('click', function(e){
$(this).off("mousemove").find('.placement').removeClass('placement')
});
Change the placement offset to
$('.placement').css({'top': relY + 30,'left': relX - 75 , 'position': 'absolute'});
Demo

Absolute position of an element on the screen using jQuery

How do I find out the absolute position of an element on the current visible screen (viewport) using jQuery?
I am having position:relative, so offset() will only give the offset within the parent.
I have hierarchical divs, so $("#me").parent().offset() + $("#me").offset() doesn't help either.
I need the position in the window, not the document, so when the document is scrolled, the value should change.
I know I could add up all the parent offsets, but I want a cleaner solution.
var top = $("#map").offset().top +
$("#map").parent().offset().top +
$("#map").parent().parent().offset().top +
$("#map").parent().parent().parent().offset().top;
Any ideas?
Update:
I need to get the exact gap in pixels between the top of my div and the top of the document, including padding/margins/offset?
My code:
HTML
<div id="map_frame" class="frame" hidden="hidden">
<div id="map_wrapper">
<div id="map"></div>
</div>
</div>
CSS
#map_frame{
border:1px solid #800008;
}
#map_wrapper {
position:relative;
left:2%;
top:1%;
width:95%;
max-height:80%;
display:block;
}
#map {
position:relative;
height:100%;
width:100%;
display:block;
border:3px solid #fff;
}
jQuery to resize the map to fill the screen*
var t = $("#map").offset().top +
$("#map").parent().offset().top +
$("#map").parent().parent().offset().top +
$("#map").parent().parent().parent().offset().top;
$("#map").height($(window).height() - t - ($(window).height() * 8 / 100));
Thanks...
See .offset() here in the jQuery doc. It gives the position relative to the document, not to the parent. You perhaps have .offset() and .position() confused. If you want the position in the window instead of the position in the document, you can subtract off the .scrollTop() and .scrollLeft() values to account for the scrolled position.
Here's an excerpt from the doc:
The .offset() method allows us to retrieve the current position of an
element relative to the document. Contrast this with .position(),
which retrieves the current position relative to the offset parent.
When positioning a new element on top of an existing one for global
manipulation (in particular, for implementing drag-and-drop),
.offset() is the more useful.
To combine these:
var offset = $("selector").offset();
var posY = offset.top - $(window).scrollTop();
var posX = offset.left - $(window).scrollLeft();
You can try it here (scroll to see the numbers change): http://jsfiddle.net/jfriend00/hxRPQ/
For the absolute coordinates of any jquery element I wrote this function, it probably doesnt work for all css position types but maybe its a good start for someone ..
function AbsoluteCoordinates($element) {
var sTop = $(window).scrollTop();
var sLeft = $(window).scrollLeft();
var w = $element.width();
var h = $element.height();
var offset = $element.offset();
var $p = $element;
while(typeof $p == 'object') {
var pOffset = $p.parent().offset();
if(typeof pOffset == 'undefined') break;
offset.left = offset.left + (pOffset.left);
offset.top = offset.top + (pOffset.top);
$p = $p.parent();
}
var pos = {
left: offset.left + sLeft,
right: offset.left + w + sLeft,
top: offset.top + sTop,
bottom: offset.top + h + sTop,
}
pos.tl = { x: pos.left, y: pos.top };
pos.tr = { x: pos.right, y: pos.top };
pos.bl = { x: pos.left, y: pos.bottom };
pos.br = { x: pos.right, y: pos.bottom };
//console.log( 'left: ' + pos.left + ' - right: ' + pos.right +' - top: ' + pos.top +' - bottom: ' + pos.bottom );
return pos;
}
BTW, if anyone want to get coordinates of element on screen without jQuery, please try this:
function getOffsetTop (el) {
if (el.offsetParent) return el.offsetTop + getOffsetTop(el.offsetParent)
return el.offsetTop || 0
}
function getOffsetLeft (el) {
if (el.offsetParent) return el.offsetLeft + getOffsetLeft(el.offsetParent)
return el.offsetleft || 0
}
function coordinates(el) {
var y1 = getOffsetTop(el) - window.scrollY;
var x1 = getOffsetLeft(el) - window.scrollX;
var y2 = y1 + el.offsetHeight;
var x2 = x1 + el.offsetWidth;
return {
x1: x1, x2: x2, y1: y1, y2: y2
}
}

Trying to make a div appear in the centre of a scrollable page - bug in my code?

Just as a preface to make sure I am clear, I don't want the div to appear dead centre in the middle of the page, I want it in the middle of the viewable window. So if you imagine a long page and the user has scrolled down to near the bottom and clicks the button the div will appear in the centre of the screen near the bottom of the page.
here is my code, which doesn't work in chrome:
function centerdiv() {
var scrolledX, scrolledY;
scrolledX = document.body.scrollLeft;
scrolledY = document.body.scrolltop;
var centerX, centerY;
centerX = document.body.clientWidth;
centerY = document.body.clientHeight;
var leftoffset = scrolledX + (centerX - 100) / 2;
var topoffset = scrolledY + (centerY - 100) / 2;
$('.current div[name="popup"]').css({'top' : topoffset + 'px', 'left':
leftoffset + 'px'});}
$(function() {
$("html").ajaxStart(function() {
centerdiv();
$(".current div[name=popup]").show();
});
$("html").ajaxComplete(function() {
$(".current div[name=popup]").hide();
});
});
Note, this is for an iphone mobile website and the ajaxstart function attaching to the html is crucial as it doesn't work on the iphone any other way on my website.
You forget to set position to absolute, or fixed
$('.current div[name="popup"]').css({'top' : topoffset + 'px', 'left':
leftoffset + 'px', 'position':'absolute' });}
Here is my solution that works fine:
var winH = $(window).height();
var winW = $(window).width();
$(this).css('top', winH/2 - $(this).height()/2);
$(this).css('left', winW/2 - $(this).width()/2);
$(this).show();
$(this) must refer to the DIV element you want to show in the center.
wh = $(window).height();
dh = $("#div").height();
$("#div").css("top",(wh - dh)/ 2 + $(window).scrollTop() + 'px');
Edit:
Not the same for width, it's actually:
ww = $(width).width();
dw = $("#div").width();
$("#div").css("left",(ww - dw)/ 2 + 'px');
But it really depends if you have a fixed viewport or not, there are many ways to center it...
Good Luck!
If you don't have horizontal scrolling you can do it partially with straight CSS
div{
left: 50%;
margin-left: -[box_width / 2]px;
}

Categories