Finding an element's position using javascript - javascript

Hi guys i have following code which is i am using to create a simple tooltip.
html
<div class="x">
<div class="abc">abc</div>
</div>
javascript
//Finding the elements position
var elmPosition = function (elm) {
var x = 0,
y = 0;
while (elm) {
x += (elm.offsetLeft - elm.scrollLeft + elm.clientLeft);
y += (elm.offsetTop - elm.scrollTop + elm.clientTop);
elm = elm.offsetParent;
}
return {
x: x,
y: y
};
};
//Creating and adding the tooltip to document
document.querySelector('.abc').addEventListener("mouseover", function () {
var elm = document.createElement("div");
var position = elmPosition(document.querySelector('.abc'));
elm.textContent = 'just a tooltip';
elm.classList.add('tooltip');
document.body.appendChild(elm);
elm.style.position = 'absolute';
elm.style.top = (position.y - 20) + 'px';
});
//remove tooltip on mouse out
document.querySelector('.abc').addEventListener("mouseout", function () {
document.body.removeChild(document.body.querySelector('.tooltip'));
})
DEMO
The generated tooltip should always stay top of the mouse hovered element. This code perfectly works until the page is scrolled. When then page is scrolled the position of the tooltip is pushed to very far from the mouse hovered element. Could someone please help me to find out what the issue is. Thanks :)

What you're checking for using scrollLeft is how far elm is scrolled. What you want is how far the window is scrolled I'm guessing.
Use window.pageYOffset and window.pageXOffset like so:
while (elm) {
x += (elm.offsetLeft - window.pageXOffset + elm.clientLeft);
y += (elm.offsetTop - window.pageYOffset + elm.clientTop);
elm = elm.offsetParent;
}
EDIT
After trying it out it doesn't make much sense involving the scroll if you're not working with position: fixed. I removed it and edited your fiddle: https://jsfiddle.net/mg606dh1/2/
EDIT 2
You can also change the position to position: fixed and use the code the way you meant for it to be used: https://jsfiddle.net/mg606dh1/3/

Related

How can I inject a div into a webpage that moves on window resize?

Essentially, I'm creating a custom click & drag selection box. The problem is that the div is position absolutely, so it will scroll with the page, but it will not move with the page when the window is being resized. My attempted solution was to listen to the window resize, and move the div according to the change. The problem is that it will SEEM to work, but it will not move entirely accurately, so it will slowly move out of place if the window is resized slowly, or quickly move out of place if the window is resized quickly. It seems that the resize listener does not capture every resize event. I've narrowed the code down to the concept I'm using.
Try injecting this script into a page (I'm using the Chrome console and I haven't made any attempt for cross-compatibility because this will be used in a Chrome extension). It will attempt to resize only when the scrollbar is not active, to replicate the behavior of the page content. The client and scoll variables are interchangeable for recording the change in dimensions, but they are both there for testing purposes. I would love to see a solution which solves this problem using styling attributes. Thanks for your help!
var div = document.createElement("div");
div.style.position = "absolute";
div.style.backgroundColor = "#000";
div.style.width = div.style.height = div.style.left = div.style.top = "200px";
document.body.appendChild(div);
// get the highest z index of the document
function highestZIndex() {
var elems = document.getElementsByTagName("*");
var zIndex = 0;
var elem, value;
for (var i = 0; i < elems.length; i++) {
value = parseInt(document.defaultView.getComputedStyle(elems[i], null).zIndex, 10);
if (value > zIndex) {
zIndex = value;
elem = elems[i];
}
}
return {
elem: elem,
zIndex: zIndex
};
}
// set the div on top if it is not already
var highestZ = highestZIndex();
if (highestZ.elem != div) div.style.zIndex = highestZ.zIndex + 1;
// last width & height of client & scroll to calculate the change in dimensions
var clientWidth = document.body.clientWidth;
var clientHeight = document.body.clientHeight;
var scrollWidth = document.body.scrollWidth;
var scrollHeight = document.body.scrollHeight;
// move the div when the window is being resized
function resizeListener() {
var _clientWidth = document.body.clientWidth;
var _clientHeight = document.body.clientHeight;
var _scrollWidth = document.body.scrollWidth;
var _scrollHeight = document.body.scrollHeight;
// horizontal scrollbar is not enabled
if (_scrollWidth <= _clientWidth) {
div.style.left = parseInt(div.style.left.replace(/px/, ''), 10) + (_scrollWidth - scrollWidth) / 2 + 'px';
}
// vertical scrollbar is not enabled
if (_scrollHeight <= _clientHeight) {
div.style.top = parseInt(div.style.top.replace(/px/, ''), 10) + (_scrollHeight - scrollHeight) / 2 + 'px';
}
clientWidth = _clientWidth;
clientHeight = _clientHeight;
scrollWidth = _scrollWidth;
scrollHeight = _scrollHeight;
}
window.addEventListener("resize", resizeListener);
PS: Please, no jQuery solutions.
Since the resize listener isn't quite dependable with outside events, I've developed a simple "hack" to get the wanted results. The window overflow is forced to scroll and the body width & height are set to +1 so that the scrollbar is active, in which the div will then stay in place. Once the resize is complete, the overflow and body dimensions are restored. This may not be a desired solution for others who want the div to move on a manual window resize, but I am invoking the resize from JavaScript so it works perfectly for me.
The script in practice:
var overflow, overflowX, overflowY, bodyWidth, bodyHeight;
function startResize() {
// store the original overflow values
overflow = document.body.style.overflow;
overflowX = document.body.style.overflowX;
overflowY = document.body.style.overflowY;
bodyWidth = document.body.style.width;
bodyHeight = document.body.style.height;
// force the scrollbar
document.body.style.overflow = "scroll";
// activate the scrollbar
document.body.style.width = document.client.width + 1 + "px";
document.body.style.height = document.client.height + 1 + "px";
}
function stopResize() {
// restore the original overflow values; x & y are included because enabling the global overflow will update x and y
document.body.style.overflow = overflow;
document.body.style.overflowX = overflowX;
document.body.style.overflowY = overflowY;
// restore the original body width & height
document.body.style.width = bodyWidth;
document.body.style.height = bodyHeight;
}

How would you use anchor points in a div when using the flexcroll plugin?

I want to have a custom scrollbar on my main div which has buttons to go to certain parts of the div, however anchor points don't seem to work when using the flexcroll plugin (I know i'm doing anchor points correctly because when I disable flexcroll on that div they work fine)
Is their any method I could use to set up the anchor points?
EDIT FOUND SOLUTION: On the buttons I want to click to go to the specific place in the document I can put onclick="Wrapper.fleXcroll.setScrollPos(false,0);"
I've used this function in the past. FYI, I don't know anything about flexcroll, so this is not tested with that:
var isInt = function(val) {
return (parseInt(val, 10) == val);
};
var scrollTo = function(node) {
var pNode = node.parentNode;
var offset = node.offsetTop - pNode.offsetTop;
var pHeight = pNode.clientHeight;
var height = node.clientHeight;
var scrollOffset = pNode.scrollTop;
var buffer = 10;
var scroll = null;
if (scrollOffset > offset) {
scroll = offset - buffer;
} else if (pHeight + scrollOffset < offset + height + buffer) {
scroll = offset + height + buffer - pHeight;
}
if (isInt(scroll)) {
pNode.scrollTop = scroll;
}
};
This is the pure JS version. (example)
Here is an example of a jQuery version, which animates the scroll event: jQuery version

clientX and clientY not giving correct mouse pointer location

I wrote this simple code to print a small dot on the location where I clicked with the mouse pointer:-
$(document).ready(function(){
$('#pane').click(function(e){
var pixel = $('<div />')
.addClass('pixel')
.css({
top: e.clientY,
left: e.clientX
});
$('#pane').append(pixel)
});
});
See this fiddle I created. When I click anywhere inside the rectangle, a small dot is printed in that location. But the problem is that dot is not printed where the mouse pointer's tip was. See the below image to see what I meant:-
I tried in both Firefox and Chrome.
Your code is working correctly,
Zoom your page and check,
i have changed pixel height and width for better understanding from 2px to 3px.
and drawing from e.clientX -1 and e.clientY -1 position so it looks exactly center.
You can find Fiddle
The most examples I've found don't work if there are a scrolled page... I used this algorythm in order to get the position:
var getOffsets = function($event){
var p = {};
var body = "search the document for the body element";
p.x = body.offsetLeft;
p.y = body.offsetTop;
while (body.offsetParent) {
p.x = p.x + body.offsetParent.offsetLeft;
p.y = p.y + body.offsetParent.offsetTop;
if (body == document.getElementsByTagName("body")[0]) {
break;
}
else {
body = body.offsetParent;
}
}
return p;
}
However, after that you have to consider also other elements, im my case:
var GetExactClickPosition = function($event){
var tr = $($event.target);
if ($event.target.localName != 'tr'){
tr = $($event.target).closest('tr');
}
var listDiv = $($event.target).closest('div');
var p = getOffsets($event);
var container = $('#mailingListExcludeMenuContainer');
container.css({
top: p.y - listDiv.scrollTop() - tr.height() - container.height() + $event.offsetY + "px",
left: p.x + $event.offsetX + "px"
});
container.show();
};
I have a list with scroller inside the main scroller of the page...
I used it in order to show a little menu at the position of the mouse click.

How to get amount of portions of a HTML element is visible in viewport

Is it possible to know whether or not an HTML element like image is viewable in current viewport or it will be visible on scroll?
If it is viewable completely or partially then how can I get the amount of portions is visible?
I am trying to explain it from the following image:
The two images at the bottom is partially visible within the viewport and these will be completely visible if one scroll down a little bit.
Now I want to get the the aforesaid information.
In the actual scenario I am trying to get the popup-zoom effect on hover of image in my album like google image search. Everything is fine, except if the images are placed in the described manner then the zoomed div also displaying in half.
Normal condition where image is completely in viewport:
And partially in viewport:
I really appreciate your help.
The code:
var albumDetailOnReady = function() {
$('.image').each(function(){
var photo = $(this);
var wrap = $(findParentByClassName(document.getElementById(photo.attr('id')), 'wrap'));
var row = $(findParentByClassName(document.getElementById(wrap.attr('id')), 'albumDetailRow'));
var visibleZone = $(wrap).find('.alDtlColumn');
var pictureBlock = $(visibleZone).find('.pictuteBlock');
var hiddenZone = $(wrap).find('.hiddenZone');
$(photo).load(function(){
if(177 > $(photo).width()){
var imgleft = ($(pictureBlock).width() - $(photo).width())/2 + 'px';
$(photo).css({'left': imgleft});
}
});
$(photo).hover(function(){
var y;
if($(photo).height() > $(photo).width()) {
y = ($(visibleZone).offset().top - 50) + 'px';
} else {
y = ($(visibleZone).offset().top + 50) + 'px';
}
var x;
if($(row).find('.wrap:first').attr('id') === $(wrap).attr('id')) {
x = ($(visibleZone).offset().left - 10) + 'px';
} else if($(row).find('.wrap:last').attr('id') === $(wrap).attr('id')) {
x = ($(visibleZone).offset().left - 50) + 'px';
} else {
x = ($(visibleZone).offset().left - 20) + 'px';
}
$(hiddenZone).css({
'top': y,
'left': x,
'position': 'absolute',
'z-index': '10'
});
$(hiddenZone).fadeIn('fast');
}, function(){
});
$(hiddenZone).hover(function(){},function(){
$(hiddenZone).hide().stop(true, true);
});
});
}
var findParentByClassName = function(element, clazz) {
while (element.parentNode) {
element = element.parentNode;
if (hasClass(element, clazz)) {
return element;
}
}
return null;
}
function hasClass(element, cls) {
var regex = new RegExp('\\b' + cls + '\\b');
return regex.test(element.className);
}
I am unable to show any HTML as I haven't have any, I am working in ADF framework.
But for an explanation:
I have two zone for each image: visible and hidden. Both of them are in a wrap. Now on hover an image I am showing the hidden div. The top and left of the hidden div is measured by the top and left of the visible div with some condition.
jQuery.Viewport
Very helpfull and lightweight jQuery plugin that makes an element as a handy viewport for displaying elements with absolute position. The plugin is hosted on GitHub. You can see it in action right there:
https://github.com/borbit/jquery.viewport

Create a mark on an image using relative positioning?

I'd like to be able to mark an image where a user clicks, store the coordinates, and then be able to recreate the marks at a later time. I've got the storing part down but I'm having trouble getting the mark image to show up on the image.
I found a similar question here using absolute positioning, but I'd like the coordinates to be relative to the image.
Looks like jQuery position will give me the position relative to the parent, but from there how would I create and position the mark image relative to the parent? Any help would be greatly appreciated. Thanks
<div id="container">
<img id="imgtoclick"></img>
</div>
$(document).ready(function() {
$("#imgtoclick").click(function(e) {
e.preventDefault();
var left = this.position.left;
var top = this.position.top;
//how to create mark image relative to parent
var img = $('<img>');
})
});
Following #Blenders post but in case your images are nested within positioned elements, you will need to get the coordinates recursively:
var myImg = ...
var getAbsoluteOffset = function (el) {
var x=0, y=0;
while (el) {
x += el.offsetLeft;
y += el.offsetTop;
el = el.offsetParent;
};
return {x:x,y:y};
}
myImg.onclick = function(evt) {
var offset, x, y;
offset = getAbsoluteOffset(this);
var x = evt.pageX - offset.x;
var y = evt.pageY - offset.y;
alert('x: ' + x + '\ny: ' + y);
};
This should do what you want:
$('img').click(function(event) {
var x = event.pageX - this.offsetLeft;
var y = event.pageY - this.offsetTop;
alert('X: ' + x + '\nY:' + y);
});
You would follow these steps:
Give #container this style
container
{
position: relative;
}
Give the image that will show the mark this style
mark
{
position: absolute;
left: //left from jQuery
top: //top from jQuery position
}

Categories