div follow cursor based on parent div not pageY - javascript

How can i get the div to follow the cursor not based on page height, the way i currently have it the div gets further away from the cursor as i scroll, i need it to stay with it at all times, i have tried a few things but none seem to work. here is a link to what i have made https://www.poshcloud.co.uk/posh-hero/
this is the function im using
document.addEventListener('mousemove', function(e) {
const circle = document.querySelector('.cursor__ball--big');
const left = e.pageX;
const top = e.pageY;
circle.style.left = left + 'px';
circle.style.top = top + 'px';
});

Using clientX and clientYshould solve your issue
document.addEventListener('mousemove', function(e) {
const circle = document.querySelector('.cursor__ball--big');
const left = e.clientX;
const top = e.clientY;
circle.style.left = left + 'px';
circle.style.top = top + 'px';
});
.cursor__ball--big {
background-color: red;
height: 100px;
width: 100px;
border-radius: 50px;
position: absolute;
left: 0;
top: 0;
transform: translate(-50%, -50%);
}
<div class="cursor__ball--big"></div>

Related

How to fix this javascript onmousemove that is not working only on wordpress site

Im trying to create a ball that follow the cursor inside my site: www.effevisual.altervista.org using wordpress and divi theme.
I tried this code lot of times without any problem but actually it looks like the objects block the ball.
I also want if possible to change the ball to less opacity when the cursor is hover a link.
<body onload = "followMouse();">
<div class="wrap">
<div id="ball"></div>
</div></body>
.wrap {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
#ball {
width: 20px;
height: 20px;
background: #0034fc;
border-radius: 50%;
position: absolute;
left: 50%;
top: 50%;
margin: -10px 0 0 -10px;
pointer-events: none;
}
var $ = document.querySelector.bind(document);
var $on = document.addEventListener.bind(document);
var xmouse, ymouse;
$on('mousemove', function (e) {
xmouse = e.clientX || e.pageX;
ymouse = e.clientY || e.pageY;
});
var ball = $('#ball');
var x = void 0,
y = void 0,
dx = void 0,
dy = void 0,
tx = 0,
ty = 0,
key = -1;
var followMouse = function followMouse() {
key = requestAnimationFrame(followMouse);
if(!x || !y) {
x = xmouse;
y = ymouse;
} else {
dx = (xmouse - x) * 0.125;
dy = (ymouse - y) * 0.125;
if(Math.abs(dx) + Math.abs(dy) < 0.1) {
x = xmouse;
y = ymouse;
} else {
x += dx;
y += dy;
}
}
ball.style.left = x + 'px';
ball.style.top = y + 'px';
};
</script>
Any message error, just the ball doesnt follow properly.
So what I found is that you are applying a transform to the class .et_pb_code_0. transform: translateX(-89px) translateY(-81px) rotateX(0deg) rotateY(0deg) rotateZ(90deg); That alone has sent your ball to a different direction making left and right up and down and up and down now left and right.
Aside from that your wrapper and ball class are contained in many other divs which position it away from the top left of the page.
I can fix it in inspecter by dragging the wrap class to the top under the main-content1 class.
You will also have to apply position:fixed to the wrap class to keep it on the screen at all times. And a z-index for the lower parks of the page. And pointer-events:none so you can click links.
And something like this to get you started:
jQuery( "li" ).mouseenter(function() {
jQuery( "#ball" ).fadeTo( "slow" , 0, function() {
// Animation complete.
});
});
jQuery( "li" ).mouseleave(function() {
jQuery( "#ball" ).fadeTo( "slow" , 1, function() {
// Animation complete.
});
});

Recalculate scrolling div position when used in a clipping path

I am using clipping paths to change my logo colour base on the background colour.
In addition to this the logo scrolls from top to bottom based on the users vertical position on the page. Top of page = logo at top, bottom of page = logo at bottom etc.
Unfortunately when I added the clipping paths the logos lost their scroll position and after the first one, do not work at all.
Is there a way around this? Also, the logo position was a little off to start with so if there is any way of addressing this at the same time.
You can see the original question here:
div position based on scroll position
I have tried this, but I can't seem to get it to work.
Scroll position lost when hiding div
I am using Advanced Custom Fields and each sections PHP file has this in the header as part of the clipping path using either the white or dark version of the logo accordingly. Its parent is positioned relatively and its child absolutely.
div class="logo-scroll">
<div class="scroll-text">
<img width="53px" height="260px" src="/wp-content/uploads/2019/07/sheree-walker-web-design-edinburgh-vertical-01.svg"/>
</div>
</div>
The Javascript
const docHeight = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
const logo = document.querySelector('.scroll-text');
const logoHeight = logo.offsetHeight;
// to get the pseudoelement's '#page::before' top we use getComputedStyle method
const barTopMargin = parseInt(getComputedStyle(document.querySelector('#page'), '::before').top);
let viewportHeight, barHeight, maxScrollDist, currentScrollPos, scrollFraction;
logo.style.top = barTopMargin + 'px';
window.addEventListener('load', update);
window.addEventListener('resize', setSizes);
document.addEventListener('scroll', update);
setSizes();
function update() {
currentScrollPos = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
scrollFraction = currentScrollPos / (docHeight - viewportHeight);
logo.style.top = barTopMargin + (scrollFraction * maxScrollDist) + 'px';
}
function setSizes() {
viewportHeight = window.innerHeight;
// to get the pseudoelement's '#page::before' height we use getComputedStyle method
barHeight = parseInt(getComputedStyle(document.querySelector('#page'), '::before').height);
maxScrollDist = barHeight - logoHeight;
update();
}
The CSS
.logo-scroll .scroll-text img {
padding: 0 6px 0 17px;
}
#page::before {
content: "";
position: fixed;
top: 30px;
bottom: 30px;
left: 30px;
right: 30px;
border: 2px solid white;
pointer-events: none;
-webkit-transition: all 2s; /* Safari prior 6.1 */
transition: all 2s;
}
.logo-scroll {
position: fixed;
left: 30px;
top: 30px;
bottom: 30px;
border-right: 2px solid white;
width: 75px;
z-index: 10;
}
.scroll-text {
position: fixed;
}
let logos, logoHeight, barTopMargin;
let viewportHeight;
window.addEventListener('load', init);
window.addEventListener('resize', setSizes);
document.addEventListener('scroll', update);
function init(lockUpdate) {
logos = document.querySelectorAll('.scroll-text');
setSizes(lockUpdate);
}
function update() {
// ensure initialization and prevent recursive call
if (!logos) init(true);
//*************************************************
/**************************************************
THIS LINE MUST BE HERE.
**************************************************/
let maxScrollDist = document.documentElement.scrollHeight - viewportHeight;
//*************************************************
let currentScrollPos = document.documentElement.scrollTop;
let newTop;
let middle = currentScrollPos + viewportHeight/2;
let middleY = maxScrollDist/2;
if (middle >= (maxScrollDist+viewportHeight)/2) {
let p = (middleY - Math.floor(middle - (maxScrollDist+viewportHeight)/2))*100/middleY;
newTop = viewportHeight/2 - logoHeight/2;
newTop += (100-p)*(viewportHeight/2)/100;
newTop -= (100-p)*(barTopMargin +logoHeight/2)/100;
newTop = Math.max(newTop, viewportHeight/2 - logoHeight/2); /*fix*/
} else {
let p = (middleY - Math.floor(-middle + (maxScrollDist+viewportHeight)/2))*100/middleY;
newTop = barTopMargin*(100-p)/100+(viewportHeight/2 - (logoHeight/2)*p/100 )*p/100;
newTop = Math.min(newTop, viewportHeight/2 - logoHeight/2); /*fix*/
}
logos.forEach(function(el) {
el.style.top = newTop + "px";
});
}
function setSizes(lockUpdate) {
logoHeight = logos[0].offsetHeight;
barTopMargin = parseInt(getComputedStyle(document.querySelector('#page'), '::before').top);
viewportHeight = window.innerHeight;
if (lockUpdate === true) return;
update();
}
updated and tested.
to check it put this code in your console:
document.removeEventListener('scroll', update);
document.onscroll = function() {
let _logoHeight = logos[0].offsetHeight;
let _barTopMargin = parseInt(getComputedStyle(document.querySelector('#page'), '::before').top);
let _viewportHeight = window.innerHeight;
let _maxScrollDist = document.documentElement.scrollHeight - _viewportHeight;
let currentScrollPos = document.documentElement.scrollTop;
let percent100 = currentScrollPos + _viewportHeight;
let scrolledPercent = currentScrollPos * 100/_maxScrollDist;
let newTop = ((_viewportHeight - _logoHeight/2)*scrolledPercent/100);
let middle = currentScrollPos + _viewportHeight/2;
let middleY = _maxScrollDist/2; // 100
if (middle >= (_maxScrollDist+_viewportHeight)/2) {
let y1 = middleY - Math.floor(middle - (_maxScrollDist+_viewportHeight)/2);
let p = y1*100/middleY;
newTop = _viewportHeight/2 - _logoHeight/2;
newTop += (100-p)*(_viewportHeight/2)/100;
newTop -= (100-p)*(30 +_logoHeight/2)/100;
newTop = Math.max(newTop, _viewportHeight/2 - _logoHeight/2); /*fix*/
} else {
let y2 = middleY - Math.floor(-middle + (_maxScrollDist+_viewportHeight)/2);
let p = y2*100/middleY;
newTop = 30*(100-p)/100+(_viewportHeight/2 - (_logoHeight/2)*p/100 )*p/100;
newTop = Math.min(newTop, _viewportHeight/2 - _logoHeight/2); /*fix*/
}
logos.forEach(function(el) {
el.style.top = newTop + "px";
});
}
CSS fix:
custom.css :: line 767
#media (max-width: 1000px)...
.scroll-text {
padding-left: 13px;
/*width: 27px;*/
}
.scroll-text img {
/* remove it. but if necessary move it to .scroll-text rule above
width: 27px; */
}
custom.css :: line 839
#media (max-width: 599px)...
.logo-scroll {
/*display: none; why! remove it*/
}
custom.css :: line 268
.scroll-text {
position: fixed;
/* height: 280px; remove it*/
padding-left: 20px;
}
see this capture
finally, have a nice day and goodby.
You are selecting only the first 'logo-text'. Instead of:
const logo = document.querySelector('.scroll-text');
You should use querySelectorAll:
const logos = document.querySelectorAll('.scroll-text');
Then, in your scroll handler, you should move them all.
So, you would then substitute each instance of usage of logo with a loop through the all the logo elements:
logos.forEach(logo => logo.style.top = ...);
Please be aware that you are doing quite expensive stuff in a scroll handler, which is not great for rendering performance. You might also want to use requestAnimationFrame to improve the rendering performance. Check out the reference page on MDN. Actually, I quickly whipped a version using requestAnimationFrame but there was no sensible performance improvement. This is probably due to the fact that apparently rAF fires roughly at the same rate than the scroll event. Anyway, I removed it to avoid confusion. If you detect performance issues, let me know.
I suggest, though, that you move the logo using transform: translate() rather than top. Here you have a complete solution. I tried it in Chrome.
const docHeight = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
const logos = document.querySelectorAll('.scroll-text');
const logoHeight = logos[0].offsetHeight;
// to get the pseudoelement's '#page::before' top we use getComputedStyle method
const barTopMargin = parseInt(getComputedStyle(document.querySelector('#page'), '::before').top);
let viewportHeight, barHeight, maxScrollDist, currentScrollPos, scrollFraction;
window.addEventListener('load', update);
window.addEventListener('resize', setSizes);
document.addEventListener('scroll', update);
setSizes();
function update() {
currentScrollPos = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
scrollFraction = currentScrollPos / (docHeight - viewportHeight);
const translateDelta = barTopMargin + (scrollFraction * maxScrollDist);
logos.forEach(logo => logo.style.transform = `translateY(${translateDelta}px)`);
}
function setSizes() {
viewportHeight = window.innerHeight;
// to get the pseudoelement's '#page::before' height we use getComputedStyle method
barHeight = parseInt(getComputedStyle(document.querySelector('#page'), '::before').height);
maxScrollDist = barHeight - logoHeight;
update();
}

Dragover: Can't move to left and top

I have an element which I would like to move with the mouse.
var troll = document.getElementById('troll');
troll.addEventListener('dragover', (e) => {
e.preventDefault();
e.target.style.left = e.clientX + 'px';
e.target.style.top = e.clientY + 'px';
}, false);
img {
width: 100px;
cursor: pointer;
position: absolute;
}
<div id="troll">
<img src="http://images.mmorpg.com/features/7909/images/Troll.png" alt="Troll">
</div>
From left to right and from top to bottom it works OK. Not perfect, since the very first move takes a whole space and it doesn't look smooth. But the main problem is that I can't move from right to left or from bottom to top.
Any help would be appreciated.
You wanna use drag not dragover, and some logic to know where you're going up or down or left or top.
var troll = document.getElementById('troll');
var X,Y = 0;
troll.addEventListener('drag', (e) => {
e.preventDefault();
if (e.clientX > X)
{
e.target.style.left = X + 'px';
}
else if (e.clientX < X)
{
e.target.style.left = X-- + 'px';
}
if (e.clientY > Y)
{
e.target.style.top = Y + 'px';
}
else if (e.clientY < Y)
{
e.target.style.top = Y-- + 'px';
}
X = e.clientX;
Y = e.clientY;
}, false);
img {
width: 100px;
cursor: pointer;
position: absolute;
}
<div id="troll">
<img src="http://images.mmorpg.com/features/7909/images/Troll.png" alt="Troll">
</div>

How do I position a div relative to the mouse pointer exactly when scroll page?

I found this example on my search.
But it is useless, because when the webpage has long height, and my <div> block isn't on the top, when I scroll the page, there are different distances with different PageY or clientY, so the movable <div> can not exactly go after the mouse cursor.
Here's what I've tried so far:
jQuery("#requestStatusChart").mouseover(function (event) {
var maskVal = '<span id="floatTip" style="position:absolute"><span id="hintdivlogistics" class="RMAHintdivlogistics">' +
+'</span><div class="clear"></div></span>';
jQuery(this).find(".DashboardMask").append(maskVal)
ShowHintInfoLogistics("abc");
//when onmouse out ,remove the elements I appended before.
jQuery(this).find(".DashboardMask").mouseout(function () {
if (typeof jQuery("#hintdivlogistics") != undefined) {
jQuery("#floatTip").fadeOut("slow").remove();
}
});
//move current row
jQuery(this).find(".DashboardMask").mousemove(function (event) {
_xx = event.clientX;
_yy = event.clientY;
_yyPage = event.pageY;
var pos = jQuery(this).position();
console.log((pos.left + " " + pos.top));
jQuery("#floatTip").css({ "top": _yy + "px", "left": _xx - 180 + "px",
"border": "2px solid red"
}).fadeIn("slow");
console.log("x:" + _xx + ",y:" + _yy / _yyPage * _yy);
return false;
});
return false;
});
I don't know of any way to do that reliably, given that you don't know the position of the mouse without a mouse event. You could keep track of the mouse position on mousemove, but as this snippet demonstrates it's far from ideal.
function mousemoved(event) {
var f = document.querySelector('#floater');
console.log(event);
f.style.top = event.pageY + f.scrollTop + 'px';
f.style.left = event.pageX + 'px';
}
document.querySelector('#container').addEventListener('mousemove', mousemoved);
#container {
overflow: scroll;
position: relative;
}
#content {
height: 4000px;
background: lightblue;
}
#floater {
position: absolute;
border: 1px solid black;
padding: 1em 2em;
}
<div id="container">
<div id="floater">Hi</div>
<div id="content">content just to make the container taller</div>
</div>
I have solved this problem use another way.
in X axis we can do like this.
content means your main program width,codes adapted all resolution.
var widthContent = jQuery("#content").width();
jQuery("#floatTip").css("left", _xx - (window.screen.width - widthContent)/2 + "px");

How to add a text box popup (Jquery tooltip or similar) to a Fabric JS image within a canvas?

I'm working on a Fabric JS project to map a floor with its rooms' locations.
At each room location I added an icon. I want to have a text box pop up (such as jquery tooltip) each time the mouse hover above the icon.
The text box should show room information (phone number \ person \ size \ etc.)
I found this google group post, but no one really described the solution beside sharing this link
Step 1: Set up your watchers
Step 2: Load the dialog
Step 3: Figure out where the bounding rect is on the page and move the dialog.
canvas.observe('mouse:over', function (e) {
console.log("Everyday I'm hovering");
showImageTools(e.target);
});
canvas.observe('mouse:out', function (e) {
$('#imageDialog').remove();
});
function showImageTools (e) {
var url = 'dialog/imageDialog.htm';
$.get(url, function(data) {
// Don't add it twice
if (!$('#imageDialog').length) {
$(body).append(data);
}
moveImageTools();
});
function moveImageTools () {
var w = $('#imageDialog').width();
var h = $('#imageDialog').height();
var e = canvas.getActiveObject();
var coords = getObjPosition(e);
// -1 because we want to be inside the selection body
var top = coords.bottom - h - 1;
var left = coords.right - w - 1;
$('#imageDialog').show();
$('#imageDialog').css({top: top, left: left});
}
function getObjPosition (e) {
// Get dimensions of object
var rect = e.getBoundingRect();
// We have the bounding box for rect... Now to get the canvas position
var offset = canvas.calcOffset();
// Do the math - offset is from $(body)
var bottom = offset._offset.top + rect.top + rect.height;
var right = offset._offset.left + rect.left + rect.width;
var left = offset._offset.left + rect.left;
var top = offset._offset.top + rect.top;
return {left: left, top: top, right: right, bottom: bottom};
}
That should be enough to get you started. Let me know if any of this doesn't make sense.
Add span element below the canvas
<span ref="toolTip" class="toolTip">ToolTip</span>
Add style for span element
NB: Visibility is hidden by default
.toolTip{
position: absolute;
z-index: 1;
background: rgb(119, 128, 0);
height: 30px;
width: 120px;
padding: 8px;
font-size: 13px;
color: #fff;
visibility: hidden;
}
Add mouse over and mouse out events
this.$data.canvas.on('mouse:over', function (e) {
// console.log(e.e.offsetX)
if (e.target && e.target.feature === 'Seat') {
self.$refs.toolTip.innerHTML =
'Seat: ' + e.target.label + ' Row: ' + e.target.rowLabel
self.$refs.toolTip.style.visibility = 'visible'
self.$refs.toolTip.style.top = e.e.offsetY + 'px'
self.$refs.toolTip.style.left = e.e.offsetX + 'px'
}
})
this.$data.canvas.on('mouse:out', function (e) {
self.$refs.toolTip.style.visibility = 'hidden'
})

Categories