Getting absolute position of an element in javascript - javascript

I am trying to create an overlay effect on mouseover of all elements. I wrote this js code, it works for most of the scenarios and fails under some conditions.
JS Code
$(function() {
var overlay = $("<div id='overlay'></div>").css({position:"absolute","display":"none","background":"red"});
$("body").append(overlay);
$("body").on("mouseover", function(e) {
var t = e.target;
var offset = $(t).offset();
var top = offset.top;
var left = offset.left;
var scrollx = $(window).scrollTop();
var scrolly = $(window).scrollLeft();
top -= scrolly;
left -= scrollx;
console.log(overlay); overlay.css({"top":top,"left":left,"width":"50px","height":"2px"});
overlay.show();
});
});
JS Fiddle
https://fiddle.jshell.net/go2j4fk7/12/show/light/
Failure Conditions
Trying to mouseover element inside an iframe. I use $("iframe").contents().mouseover() to bind event.
If parent element has scroll
If element is in fixed position.
How to create an overlay for any element?

Related

Check if mouse has left specific portion of window

Is it possible to know if mouse has left specific portion of the window? The values are given below:
var cursorX;
var cursorY;
document.onmousemove = function(e){
cursorX = e.pageX;
cursorY = e.pageY;
}
document.addEventListener('mouseout', function(e) {
var dims = elem.getBoundingClientRect();
var top = window.scrollY + dims.top;
var left = dims.left;
var width = dims.width;
var bottom = dims.height;
if (what condition should be here) {
console.log('yes mouse has left that portion')
document.getElementById('div-in-the-end-of-body').style .display = 'none';
}
});
For example values of dims in console log are ClientRect {top: 155.375, right: 621, bottom: 540.375, left: 313, width: 308…}
Here is visual of what I'm trying to achieve.
Edit: That div at the end of the body has absolute position and it hovers on the images. If I hover at that div images consider mouse has left it and hides the div. This is the reason I want to do it this way.
Edit # 2: Here is the solution
elem.onmouseout=function(){
var dims = this.getBoundingClientRect();
var top = window.scrollY + dims.top;
var left = dims.left;
var width = dims.width;
var bottom = dims.height;
if(top > 10 || left > 10 || width > 10 || bottom > 10){
document.getElementById('div-in-the-end-of-body').style .display = 'none';
}
}
Have a look at the mouseout event. Alternatively, you could capture mouse events as soon as your mouse has entered your specific region.
You can bind event listeners to the "regions" you want to check. As your regions are objects in javascript, there are event listeners built in or you can using obj.call to call functions not belong to the object you created. For instance,
let rects[] // this is your list of regions
for (let rect of rects) {
rect.onMouseMove((e) => {
// do something when mouse cursor is moving
})
rect.onMouseEnter((e) => {
// do somthing when mouse cursor enters the area
})
rect.onMouseLeave((e) => {
// do something when mouse cursor exits the area
})
}
Ok, I've figured out the solution. Here is working code for those who might need.
elem.onmouseout=function(){
var dims = this.getBoundingClientRect();
var top = window.scrollY + dims.top;
var left = dims.left;
var width = dims.width;
var bottom = dims.height;
if(top > 10 || left > 10 || width > 10 || bottom > 10){
console.log('yay!! ship has left the dock')
}
}

Detect the nearest divs to the center screen when scrolling jquery

I want to detect which div is nearest to the screen center, while scrolling horizontally. Once detected, I want to do something such as trigger an event.
var screenW = ($(window).width() /2);
$('div.fistSlider').bind('mousemove', function(e){
var xN = e.pageX + 16;
$('div#divContainer').scrollLeft(xN);
});
When the div nearest to red line (the center of screen), should do some event.
The answer here is to check for the offset of each div.
$(document).scroll(function(){
$('div').each(function(){
var centerLine = $(window).width()/2;
var divStart = $(this).offset().left;
var divEnd = divStart + $(this).width();
if(divStart < centerLine && divEnd > centerLine){
//do the thing
} else {
//undo the thing
};
});
});

Overriding inline CSS using jQuery applies for a while is then gone afterwards. Why?

I am trying to change the inline CSS style of top which is by default provided by jQuery using jQuery CSS() class. But it applies for a while and then it is again switched to old inline CSS top style.
Why is this happening?
see the jsfiddle.
this is what I have done:
<script>
`$(".popbutton").on('click',function(e) {
var mousex = e.pageX + 20, //Get X coodrinates
mousey = e.screenY + 20; //Get Y coordinates
var e = jQuery(this);
this.timer=setTimeout(function () {
e.popover("show");
},600);
var menu = $(".popbutton").next(),
menuWidth = menu.width(), //Find width of tooltip
menuHeight = menu.height(), //Find height of tooltip
menuVisY = $(window).height() - mousey, //Distance of element from the bottom of viewport
heightY=$(this)[0].scrollHeight-(1.2*menuHeight);
$(menu).css('top','100px');
});
});`
</script>
Because of this code:
this.timer = setTimeout(function () {
e.popover("show");
}, 600);
When you click the button, the position is calculated correctly but e.popover('show') again changes the position after a delay of 600ms.

onbeforemousemove to get mouse's old position?

I'm working on a drag and drop lib and i would like to add the mouse's position variation to the dragged element's actual position instead of just setting it's position to the current cursor position in the window. This would allow me not to use position: fixed and be able to drag position relative/absolute; elements.
To know the old position of the mouse (before the mousemove handler is called) i can just store the position in a variable in the previous call to that handler using e.pageX and pageY. But what about the first time the mouse handler is moved ? How can i know the old mouse position to determine it's variation when i havn't stored that old position yet ?
A piece of code :
var $dragged = null,
$window = $(window),
oldMouseX = null,
oldMouseY = null;
var mouseMoveHandler = function(e) {
var curTop = $dragged.css('top'),
curLeft = $dragged.css('left');
$dragged.css({
top : curTop + e.pageY - oldMouseY,
left : curLeft + e.pageX - oldMouseX,
});
oldMouseX = e.pageX;
oldMouseY = e.pageY;
};
$('.Draggable')
.attr('draggable', true)
.css({userSelect: 'none'})
.on('mousedown', function() {
$dragged = $(this);
$window.bind('mousemove', mouseMoveHandler);
})
.on('mouseup', function() {
$dragged = null;
$window.unbind('mousemove', mouseMoveHandler);
})

Auto-scroll to the bottom of a div

I have a div with overflow set to scroll which essentially streams data line by line off a file. I'd like to scroll automatically to the bottom of the div whenever the stream overflows, but without using a "Click here to scroll to bottom" button.
I already know of the scrollTop = scrollHeight solution, but that requires some kind of event trigger on the client's side. I don't want this element to be interactive; it should scroll by itself.
Is there any way to achieve this?
A lot of the scrollHeight implementations didn't work for me, offsetHeight seemed to do the trick.
Pretty sure that scrollHeight tries to move it to the bottom of the height of the static element, not the height of the scrollable area.
var pane = document.getElementById('pane');
pane.scrollTop = pane.offsetHeight;
There's no way to automatically scroll an element to the bottom. Use element.scrollTop = element.scrollHeight.
If you don't know when the element is going to resize, you could add a poller:
(function(){
var element = document.getElementById("myElement");
var lastHeight = element.scrollHeight;
function detectChange(){
var currentHeight = element.scrollHeight;
if(lastHeight != currentHeight){
element.scrollTop = currentHeight;
lastHeight = currentHeight;
}
}
detectChange();
setInterval(detectChange, 200); //Checks each 200ms = 5 times a second
})();
Some old code of mine with a running example that will stay at the bottom when new content is added, if the user scrolls it will not more it to the bottom.
var chatscroll = new Object();
chatscroll.Pane =
function(scrollContainerId)
{
this.bottomThreshold = 25;
this.scrollContainerId = scrollContainerId;
}
chatscroll.Pane.prototype.activeScroll =
function()
{
var scrollDiv = document.getElementById(this.scrollContainerId);
var currentHeight = 0;
if (scrollDiv.scrollHeight > 0)
currentHeight = scrollDiv.scrollHeight;
else
if (objDiv.offsetHeight > 0)
currentHeight = scrollDiv.offsetHeight;
if (currentHeight - scrollDiv.scrollTop - ((scrollDiv.style.pixelHeight) ? scrollDiv.style.pixelHeight : scrollDiv.offsetHeight) < this.bottomThreshold)
scrollDiv.scrollTop = currentHeight;
scrollDiv = null;
}

Categories