This question already has answers here:
jQuery x y document coordinates of DOM object
(3 answers)
Closed 8 years ago.
I have section and article for displaying contents. My code is:
<section id = "examples">
<article id="item_1">
...
</article>
<article id="item_2">
...
</article>
<article id="item_3">
...
</article>
<article id="item_4">
...
</article>
...
</section>
How can I get the x and y co-ordinates of all the articles?
Easy to do with jQuery
$('article').each(function() {
var element = $(this);
var position = element.position();
console.log( "left: " + position.left + ", top: " + position.top );
}
you can use instead pure js as #koningdavid pointed out in the same way
var elements = document.getElementsByTagName('article');
for(var i = 0; i < elements.length; i++)
{
var element = elements[i].getBoundingClientRect();
console.log( "left: " + element.left + ", top: " + element.top );
}
Live: http://jsfiddle.net/HMHbE/1/
Pure Javascript method
document.querySelector('#item_1').getBoundingClientRect() // for example for #item_1
element.getBoundingClientRect
The returned value is a TextRectangle object which is the union of the rectangles returned by getClientRects() for the element, i.e., the CSS border-boxes associated with the element.
The returned value is a TextRectangle object, which contains read-only left, top, right and bottom properties describing the border-box, in pixels, with the top-left relative to the top-left of the viewport.
https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect
You could do it with jQuery using position or offset:
$('article').each(function(){
var position = $(this).position();
console.log("top: " + position.top + " left: " + position.left);
});
LIVING DEMO
Take into account that position is relative to the document and offset calculates the coordinates relative to the parent offset element.
I would try this in javascript:
// element is each article
// then you can use element.top and element.left for the x and y
var element = document.getElementById('Item_1');
var ele = element.getBoundingClientRect();:
You can use getBoundingClientRect() javascript function
var div = document.getElementById("item_1");
var position = div.getBoundingClientRect();
alert("Coordinates: " + position.left + "px," + position.right+"px,"+ position.top + "px," + position.bottom + "px" );
Related
With this Angular project, i'm trying to create elements that can be dragged to any location within the body. I want these changes to persist.
I tried to style the dragged element with position: relative, left: {the y value of the mouse's position, and top: {the x value of the mouses position}.
This works, but because you can drag an element from its middle, the dragged element jumps because the top left corner is being placed at the location of the mouse rather than the location on the element where the mouse is hovering.
So, I am trying to offset this by finding the distance from the top left corner of the element to the location of the mouse when dragging begins, and then using the difference to slightly alter the top, left styling.
dragx: Number;
dragy: Number;
dragstart(e){
let x = e.pageX;
let y = e.pageY;
let drag = document.getElementById('drag');
let rect = drag.getBoundingClientRect();
let elX = rect.left;
let elY = rect.top;
this.dragx = elX - x;
this.dragy = elY - Y;
console.log("element position" + elX + ", " + elY);
console.log("mouse position:" + x + ", " + y);
console.log("difference" + this.dragx + ", " + this.dragy)
}
In this bit of code, i'm just trying to assign a value to the global variables that represent the difference between the mouse and the element when first dragging. These will be used in the dragover function.
dragover(e){
let mousePosition = document.getElementById('mousePosition');
let drag = document.getElementById('drag');
let dragPosition = document.getElementById('elPosition');
let x = e.pageX;
let y = e.pageY;
mousePosition.innerHTML = x + ", " + y;
let rect = drag.getBoundingClientRect();
dragPosition.innerHTML = rect.left.toString() + ", " + rect.top.toString();
drag.style.position = "absolute";
drag.style.top = y + "px";
drag.style.left = x + "px";
console.log("test" + this.dragy);
}
The problem is that when I try to access these properties, like in the last line, i'm being told that dragy and dragx are undefined.
Maybe, I have a fundamental misunderstanding of global variables or properties or something. My question is why are dragx and dragy undefined?
Also, is this a good way to make draggable elements or am I overcomplicating it, or am I going about it the wrong way?
Thanks.
--- Edit --- Where the listeners get added.
ngOnInit() {
//console.log(document);
this.dataService.getStyling().subscribe((stylings) => {
this.stylings = stylings;
});
this.el = document.getElementById('drag');
let dragP = document.getElementById('elPosition');
let rect = this.el.getBoundingClientRect();
dragP.innerHTML = rect.left.toString() + ", " + rect.top.toString();
this.el.addEventListener('dragstart', this.dragstart);
this.el.addEventListener('ondrag', this.ondrag);
document.addEventListener('dragover', this.dragover);
}
The reason is your context of this is being lost. You can use something like:
this.el.addEventListener('dragstart', this.dragstart.bind(this));
Or
this.el.addEventListener('dragstart', (e) => this.dragstart(e));
Bear in mind you will need to change all of the addEventListeners
I am trying to get the position of an element dropped onto the canvas using the following code.
var x = $(".partitiondrop").position();
alert("Top position: " + x.top + "\nLeft position: " + x.left);
The above works fine. I would like to know if I can get the Right and Bottom positions in the same way so that I can have the area bound by the element as I need to check which elements fall inside this element.
var $partitiondrop = $(".partitiondrop");
var position = $partitiondrop.position();
position.bottom = position.top + $partitiondrop.height();
position.right = position.left + $partitiondrop.width();
alert("Top position: " + position.top + "\nLeft position: " + position.left + "\nBottom position: " + position.bottom + "\nRight position: " + position.right);
U can always add width to x.left position and add height to x.top position.
To get the position of any element by its ID you can do the following
var elementID; //Already obtained via attr(id) method or so
var $element = $("#" + elementID);
var position = $element.position();
position.bottom = position.top + $element.height();
position.right = position.left + $element.width();
var top_position=position.top;
var left_position=position.left;
var bottom_position=position.bottom;
var right_position=position.right;
In Jquery, it can be done using the following code
var p = $( "elementId" );
var position = p.position();
$( "p:last" ).text( "left: " + position.left + ", top: " + position.top );
Right Position:
$(window).width() - ($('.partitiondrop').offset().left + $('.partitiondrop').width());
Bottom Position:
$(window).height() - $('.partitiondrop').offset().top;
I was wandering if any one could help me with this svg problem. How do I get the mouse coordinate version of an svg object. Usually when a user clicks on the page, the click event gets trigger and the object has a mouse position in terms of x and y. In my case, I don't want to do it with an event. Is getting the mouse position possible by simply examining the svg object's properties like the x and y coordinate? I put together an example page, hope it makes it clearer. http://jsfiddle.net/kenny12/XBCHF/ is the link. Excerpt is:
var svg = document.getElementsByTagName('svg')[0];
var pt = svg.createSVGPoint();
var el1 = document.getElementsByTagName('rect')[0];
var log_svgcursorPoint,
log_mouseclick,
log_mousecoord;
function svgcursorPoint(evt){
pt.x = evt.clientX; pt.y = evt.clientY;
var a = svg.getScreenCTM();
log_svgcursorPoint = "offset based on svg"+ " x:" + a.e +" y:" + a.f;
var b = a.inverse();
return pt.matrixTransform(b);
};
(function(elem){
elem.addEventListener('mousedown',function(e){
log_mouseclick = "mouse clicked at"+ " x:" + e.clientX +" y:" + e.clientY ;
var svgmouse = svgcursorPoint(e);
log_mousecoord = "svg mouse at"+ " x:" + svgmouse.x +" y:" +svgmouse.y;
document.getElementById('op').innerHTML = log_svgcursorPoint + "<br>" + log_mouseclick + "<br>" + log_mousecoord;
},false);
})(el1);
(function calc_manually(){
var rec = document.getElementsByTagName("rect")[0];
var root = document.getElementsByTagName("svg")[0];
var x = rec.getAttribute("x");
var y = rec.getAttribute("y");
var CTM = root.getScreenCTM();
// How to get the mouse position these information without using events is the problem.
})();
Why don't you want an event? That's what they're for. If you're dealing with mouse coordinates, just stick standard DOM event listeners on your objects and then when they trigger, use the event.target.getBoundingClientRect() function for the element's position on-screen, and the event.offsetX/screenX and event.offsetY/screenY properties for the mouse coordinates.
simple demonstrator: http://jsfiddle.net/HBmYV/1/
you can use event layer as well which works better if the svg element is positioned some where besides 0,0 on the page p.x =event.layerX || event.clientX;
I have a question concerning html button text position. As I can see it, there are ways to get left upper corner element positions but what about right upper corner. For example
I have button as:
<button style="text-align: left">Hello World</button>
...OK next I want to know what coordinates the inner text "Hello World" is ending. So is it possible to get it with js or what is the most optimal way?
Thanks
Try this:
Pure JavaScript
http://jsfiddle.net/DerekL/AYAPY/3/
//1. wrap with content <span>
var txt=document.querySelector("button").innerHTML;
document.querySelector("button").innerHTML="";
document.querySelector("button").appendChild(document.createElement("span"));
document.querySelector("button span").innerHTML=txt;
//2. Get the <span>'s coordinate
var end_y=document.querySelector("button span").offsetTop;
var end_x=document.querySelector("button span").offsetLeft+document.querySelector("button span").offsetWidth;
//3. Done!
alert(end_x+", "+end_y);
With jQuery
Highly recommended.
http://jsfiddle.net/DerekL/AYAPY/
I put a little "|" thingy at the point, just to show you the coordinate returned is correct.
Pass an element to getButtonCoords. It will return an object (let's call it coords). coords.x is the x coordinate and coords.y is the y coordinate.
/* from stackoverflow.com/questions/442404/dynamically-retrieve-html-element-x-y-position-with-javascript */
function getOffset( el ) {
var _x = 0;
var _y = 0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return { top: _y, left: _x };
}
function getButtonCoords(button) {
/* wrap the text in a span element so we can get its coordinates */
button.innerHTML = "<span id='button-text-" + button.id + "'>" + button.innerHTML + "</span>";
/* get the span element */
var button_span = document.getElementById('button-text-' + button.id);
/* get the offset */
var offset = getOffset(button_span);
/* get the coordinates */
var coords = { x: offset.left + button_span.offsetWidth, y: offset.top };
/* return them */
return coords;
}
/* get the button and pass it to the coordinate function */
var coords = getButtonCoords(document.getElementById('button-id'));
/* show the results */
alert(coords.x + ", " + coords.y);
Hi I have some elements like these:
<div id="one">content</div>
<div id="two">content</div>
and a corrispondent number of elements (without any parent, they are just after the body tag) that have:
position: absolute;
and with an id like that:
id="helper-one" refers to id="one"
Now i want to place the second group of elements exactly at the middle (vertical and horizontal) of referred elements, how can i do that?
I've tried with offset:
var one_offset = $("#one").offset();
$("#helper-one").offset({ top: one_offset.top, right: one_offset.right, left:one_offset.left, bottom: one_offset.bottom})
but it set position only for top and left positionating the helper at the top-left corner of the element and not at its center
jQuery.fn.center = function (obj) {
var loc = obj.offset();
this.css("top",(obj.outerHeight() - this.outerHeight()) / 2 + loc.top + 'px');
this.css("left",(obj.outerWidth() - this.outerWidth()) / 2 + loc.left+ 'px');
return this;
}
Call as $("#helper-one").center($("#one"));
ps: you may even skip obj argument by parsing the id of the original element
jQuery.fn.center = function () {
var obj = $('#' + this.attr('id').split('-')[1]), loc = obj.offset();
this.css("top",(obj.outerHeight() - this.outerHeight()) / 2 + loc.top + 'px');
this.css("left",(obj.outerWidth() - this.outerWidth()) / 2 + loc.left+ 'px');
return this;
}
$(document).ready(function(){
$("#helper-one").center();
});