Change position of div based on mouse pointer - javascript

I am trying to position a div based on mouse position, I managed to get it to work 50%.
The problem is that DIV always seems to be much lower than the actual mouse position, I try to minus the offset, no luck.
Basically what I want is to float the div(the NEXT link in jsfiddle) vertically, but the DIV should not be able to go outside of the container it is in(the div that has the image in the jsfiddle)
here is the jsfiddle: http://jsfiddle.net/LYmVH/7/
below is the JS, which is also in the jsfiddle:
$('.post-single-content').mousemove(function(e){
var height=e.pageY,
height1 =$('.content-top').height();
$('.btnNext').css({top: (e.pageY + 50) + "px"});
});

You need measure against the top of the parent element since it's absolutely positioned in it.
Try changing your JS to:
$('.post-single-content').mousemove(function(e){
var top = (e.pageY - $(this).offset().top) + 'px';
$('.btnNext').css({ top: top });
});
Upon reading some comments lemme update, by making use some basic math and create "collision". Somthing like:
$('.post-single-content').mousemove(function(e){
var y = e.pageY, // mouse y axis position
tHeight = $(this).height(), // container height
bHeight = $('.btnNext').height(), // button height
oTop = $(this).offset().top, // offset top position of container
abBot = tHeight - $('.btnNext').height(), // absolute top of button when at bottom
bHalf = bHeight / 2, // half button height
top = y - oTop - bHalf, // initial top pos of button
bot = y - oTop + bHalf; // bottom of button while moving
if (top < 0) top = 0; // ensure button doesn't go to far north
else if (bot > tHeight) top = abBot; // ensure it cant go past south
$('.btnNext').css({ top: top }); // 'px' not neccesary
});
jsFiddle

Related

If bottom of div is visible jquery

Please help me out here, if bottom of div or full div is visible then i want to scroll to down of next div. Here the code i have tried out,
Mathematically,
var top = $("#myDiv").offset().top;
//top = 1863
var divHeight = $("#myDiv").height();
//divHeight = 571
var total = top + divHeight;
//total = 2434
if($('#myDiv').css('height',total).visible(true))
{
alert('hi');
// I need to alert only if the full div is visible not some part of div
}
else
{
//if height of myDiv is larger window height (my screen height 640 pixels)
}
If all this part of html(from top to divHeight) or bottom of page(here total value) is visible then i need to scroll to next div.
Please note :- the code inside if conditional statement is not correct, i think you got some idea from that.
Given element the jQuery object you want to check, element is fully visible if it is shown and all of the 4 sides of its layout box fall within the window viewport.
Caution: the following solution assumes that there are no element with scrollable overflow between element and the document root, otherwise the calculation becomes way more complicated.
function isFullyVisible(element) {
var offset = element.offset();
var scrollTop = $(document).scrollTop();
var scrollLeft = $(document).scrollLeft();
return element.is(":visible") && // shown
offset.top >= scrollTop && // top
offset.left >= scrollLeft && // left
offset.top + element.outerHeight() <= scrollTop + $(window).height() && // bottom
offset.left + element.outerWidth() <= scrollLeft + $(window).width(); // right
}
If you don't care of sides, you can keep only the corresponding sub-expression.

How to position the center of a div to the center of the mouse cursor on mouse movement with JS?

I'm trying to position the center of a div element to the center of the mouse cursor, that will follow along its movements.
Already I came up with the code below, but the problem with this one is, that the following div is not positioned at the center of my cursor, but with some offset off the cursor.
WORKFLOW
The basic idea behind my code is, when the mouse enters the .post-entry div element, the .pointer within the current item should be displayed and follow the cursor of the mouse. When the mouse leaves the div it should be hidden.
CODE
HTML post item:
<article class="col-md-4 col-sm-6 post-entry">
<a href="#" title="">
<figure class="post-thumb">
<img src="http://placehold.it/300x300" alt="">
<div class="pointer" style="background: red;"></div>
</figure><!-- End figure.post-thumb -->
</a>
</article><!-- End article.col-md-4 post-entry -->
JS:
$('.entry .post-entry').each(function() {
$(this).on("mouseenter", mouseEnter);
$(this).on("mousemove", mouseMove);
$(this).on("mouseleave", mouseLeave);
});
function mouseEnter(event) {
console.log('enter');
var target = $(this);
var dot = target.find('.pointer');
var mX = (event.clientX);
var mY = (event.clientY);
set(
dot, {
x: mX,
y: mY,
force3D: !0
}
);
};
function mouseMove(event) {
console.log('move');
var target = $(this);
var dot = target.find('.pointer');
// var offset = target.offset();
// var width = target.width();
// var height = target.height();
// var top = offset.top;
// var left = offset.left;
var mX = (event.clientX);
var mY = (event.clientY);
$(dot).css('-webkit-transform', 'translate3d(' + mX + 'px, ' + mY + 'px, 0)');
};
function mouseLeave(event) {
console.log('leave');
var target = $(this);
var dot = target.find('.pointer');
$(dot).css('-webkit-transform', 'translate3d(0, 0, 0) scale(0, 0)');
};
function onClick(event) {
event.preventDefault();
console.log('click');
};
function set(el, obj) {
var dot = $(el).css('-webkit-transform', 'translate3d(' + obj.x + 'px, ' + obj.y + 'px, 0px)');
return dot;
};
PROBLEM / DEMO
As mentioned before, the span is following the mouse cursor, only the span is not positioned to the center of the cursor. It will be offset the mouse. See live demo here
I tried already something like this for the mX and mY variables, but with no succes:
var mX = (event.clientX - $(this).offset().left) / $(this).width() * $(this).width() - .125 * $(this).width();
var mY = (event.clientY - $(this).offsetTop) / $(this).height() * $(this).height() - .125 * $(this).width();
Also the answer from #hiEven doesn't work and will let me with the same issue:
transform: calc(mX - 50%, mY - 50%)
I know I should do something with dividing the .pointer by half, but how I should implement that in the code is a big question mark for me.
UPDATE
I created two new Codepen projects:
Use without images: http://codepen.io/anon/pen/GqGOLv. When you hover over the first item you will see that the brown pointer is correctly following your mouse cursor - what I am looking for. But when hovering over the second one, you will see the red pointer, only when you are at the very left side of the item.
When I use images: http://codepen.io/anon/pen/QExOkx. The problem by this example is that when you at the very top of the first column, you will see the brown pointer. When hover at the top left corner of the second item you will see a little piece of the red pointer, the same as the example without images.
Both pointer should follow the mouse cursor correctly. And I am searching for a solution that works with the use of an image.
Beside these two examples, when I add to the first one, an extra margin-left to the first item, the brown pointer will not be in the center of the mouse cursor, only when it's set to margin-left zero.
So I don't know what's missing and why it only works with the first example (without images) and only for the first item?
Try the code below
<html>
<head>
<style>
#mouse_div{
position: absolute;
background-color: black;
}
</style>
<script>
var div_width = 100;
var div_height = 100;
var div_x, div_y;
function mouse_position(event){
var mouse_x = event.clientX;
var mouse_y = event.clientY;
document.getElementById("mouse_div").style.width = div_width + "px";
document.getElementById("mouse_div").style.height = div_height + "px";
div_x = mouse_x - (div_width / 2);
div_y = mouse_y - (div_height / 2);
document.getElementById("mouse_div").style.left = div_x + "px";
document.getElementById("mouse_div").style.top = div_y + "px";
}
</script>
</head>
<body onmousemove="mouse_position(event)" onload="mouse_position(event)">
<div id="mouse_div"></div>
</body>
</html>
This program gets the position of your mouse, the width, and the height of the div. Then, it takes the x and subtracts the div's width divided by two from it (this centres the div's x position on your mouse). The program then does the same thing for the mouse y. Once all of the variables are defined, I use JavaScript to access the CSS of the div to place the div where it needs to be.
Note: you must make sure that the position of the div is set to absolute or the program will not work.
I assume you want the circle being center of your mouse, right?
try do this
transform: `translate(calc(${mx}px - 50%), calc(${my}px - 50%))
here is the demo
Based on my latest update, I did not conform to the correct formula that is needed to center the element .pointer to the mouse.
In order to use the following calculation within mouseMove:
var mX = (event.clientX);
var mY = (event.clientY);
Should be changed to this:
var height = dot.height();
var width = dot.width();
var offset = target.offset();
var w = target.width();
var h = target.height();
var top = offset.top;
var left = offset.left;
var mX = (event.clientX - left) - width / 2 - 15; // 15 = padding
var mY = (event.clientY - top) - height / 2;
So this formule is considering that the following DOM element .pointer will follow the mouse movements of the user. I don't know exactly why this working, but the offset from the previous item will be decreased from the current clientX coordinates, so the position of the second item is reset to zero, so the pointer will start at the left side of each item.
Here is a working demo of above code: http://codepen.io/anon/pen/AXdxZO?editors=0110

Scrolling based on mouse position retaining click events in the foreground

So I have a very wide div within a smaller div. The inner div scrolls left and right depending on mouse position.
I adapted the code from this answer... https://stackoverflow.com/a/6137535/3656408
There are two transparent divs on top of everything, from which the position of the mouse is attained, which gives a speed at which to scroll.
The problem with this is anything underneath these divs is not clickable.
My div has a fixed width and height so I potentially could calculate the scroll speed from where the mouse is on the page ( ie. the page is 620px wide so I know 310 is half way )
Unfortunately my maths is terrible and I can't figure out how to convert my thought process into acceptable working code.
Anyone have any suggestions?
Heres how it currently figures out the rate at which to move the page...
$('.direction', backdrop).mousemove(function(e){
var $this = $(this);
var left = $this.is('.left');
if (left){
var w = $this.width();
rate = (w - e.pageX - $(this).offset().left + 1)/w;
}
else{
var w = $this.width();
rate = -(e.pageX - $(this).offset().left + 1)/w;
}
});
.. and you can see it in action here http://thetally.efinancialnews.com/tallyassets/20years/index.html
OK I figure it out...
$( document ).mousemove(function(e){ //if mouse moves on page
if (e.pageX <= 620 && e.pageY <= 600){ //and if its not outside the extents of the div
if (e.pageX <= 310){ //if its less than half way across
rate = (310 - e.pageX)/50;
} else { // if its more than half way across
rate = -( e.pageX - 310)/50;
}
}
});

Accurate jQuery x y mouse click on image

I have a div with a background image - the div is set to the exact size of the image and my pointer is set to a crosshair over the div.
I want to mark each click with its x and y positions in the div over the image background. This I can do but the mark on the div is always lower and to the left of the actual cursor why is this?
function showClick(x,y)
{
$('.clickable').append('<span id="'+x+y+'_span" style="position: absolute;top:'+y+'px;left:'+x+'px;" class="red">+</span>');
}
$('.clickable').bind('click', function (ev) {
var $div = $(ev.target);
var offset = $div.offset();
var xMargin = ($div.outerWidth() - $div.width()) / 2;
var yMargin = ($div.outerHeight() - $div.height()) / 2;
var x = (ev.pageX + xMargin) - offset.left;
var y = (ev.pageY + yMargin) - offset.top;
showClick(x,y);
});
working example: https://jsfiddle.net/b94ypmae/3/
You are not taking into account the size of the span (and the character inside it).
Your code is working properly, in that a span is being placed in your div at the position of your cursor, but that position is based on the upper left corner
If you put a border around your span you can see it is a perfect alignment of your upper left corner: JSFiddle showing border
You could fix this by taking into account the size of the placed span(if you know it will always be the same you could hard code it as well). Here's an example of getting the size of the placed span and moving it by half it's width and height: Fixed JSFiddle
var placedSpan = $("#" + x + y + "_span");
var width = placedSpan.width();
var height = placedSpan.height();
placedSpan.css('left', x - width / 2 + 'px');
placedSpan.css('top', y - height / 2 + 'px');

Finding Image Height variable for multiple images in Jquery

I'm currently working on this script for "tooltips" on a website. I'm finding that the code I currently have will get the image height for my first tooltip image on the page ('pop1') but it ignores the rest (they come out as null).
What's the most effective way to get all the tooltip image heights, and use them every time the user scrolls over the tooltip image?
Another issue, if anyone is able to figure this one out - is that on my FULL webpage (many more divs, rows, columns, etc.) the script begins to break because clientX and clientY are being affected by the various divs and page elements.
I'd like to be able to set clientX and clientY to the exact (x, y) coordinates that the user's mouse is at, relative to the entire webpage, not relative to the page's child elements.
Thanks
Here's my JSFiddle: http://jsfiddle.net/tgs7px4f/18/
JS Code:
$('a.popper').hover(function (e) {
var target = '#' + ($(this).attr('data-popbox'));
$(target).show();
}, function () {
var target = '#' + ($(this).attr('data-popbox'));
if (!($("a.popper").hasClass("show"))) {
$(target).hide();
}
});
$('a.popper').mousemove(function (e) {
var target = '#' + ($(this).attr('data-popbox'));
// images vary in height!
// images are all 366px wide.
var imageWidth = 366;
var imageHeight = $(".popimg").height();
//alert('Image Height: ' + imageHeight);
//Offset tooltip:
//10px to the right of cursor
var imageX = e.clientX + 20;
//imageHeight up from cursor
var imageY = e.clientY - imageHeight - 20;
// Find bounds of current window, and if...
// Tooltip goes off right side:
if ((imageX + imageWidth) > $(window).width()) {
//Move tooltip left so it meets edge:
imageX = $(window).width() - imageWidth;
}
// Tooltip goes off top
if (imageY < 0) {
//Move tooltip down so it meets top:
imageY = 0;
}
$(target).css('top', imageY).css('left', imageX);
});
What's the most effective way to get all the tooltip image heights, and use them every time the user scrolls over the tooltip image?
First of all, I suppose you mean whenever a user does a mouseover on one of the elements? However, this seems to work and it cashes the height of the image directly on the element and uses it the next time a mouseover occurs:
$('a.popper').mousemove(function (e) {
var target = '#' + ($(this).attr('data-popbox'));
// images vary in height!
// images are all 366px wide.
var imageWidth = 366;
$target = $(target);
if (!$target.attr("height")) {
var img = $target.closest(".popbox").children("img");
var imageHeight = img.height();
$target.attr("height", imageHeight);
console.log("height attribute set");
} else {
var imageHeight = +($target.attr("height")) + 0;
console.log("cached height used");
}
console.log('Image Height: ', imageHeight);
//Offset tooltip:
//10px to the right of cursor
var imageX = e.clientX + 20;
//imageHeight up from cursor
var imageY = e.clientY - imageHeight - 20;
// Find bounds of current window, and if...
// Tooltip goes off right side:
if ((imageX + imageWidth) > $(window).width()) {
//Move tooltip left so it meets edge:
imageX = $(window).width() - imageWidth;
}
// Tooltip goes off top
if (imageY < 0) {
//Move tooltip down so it meets top:
imageY = 0;
}
$(target).css('top', imageY).css('left', imageX);
});
Obviously, you should remove all the console.log statements which are for testing purposes only.
jsFiddle
Regarding your second question, it's hard to say anything concrete without another jsFiddle or additional code.

Categories

Resources