Find coordinates of every link in a page - javascript

In Javascript:
How does one find the coordinates (x, y, height, width) of every link in a webpage?

Using jQuery, it's as simple as:
$("a").each(function() {
var link = $(this);
var top = link.offset().top;
var left = link.offset().left;
var width = link.offset.width();
var height = link.offset.height();
});

without jquery:
var links = document.getElementsByTagName("a");
for(var i in links) {
var link = links[i];
console.log(link.offsetWidth, link.offsetHeight);
}
try this page for a func to get the x and y values:
http://blogs.korzh.com/progtips/2008/05/28/absolute-coordinates-of-dom-element-within-document.html
However, if you're trying to add an image or something similar, I'd suggest using the a:after css selector.

Plain JavaScript:
function getAllChildren (node, tag) {
return [].slice.call(node.getElementsByTagName(tag));
}
function offset(element){
var rect = element.getBoundingClientRect();
var docEl = doc.documentElement;
return {
left: rect.left + window.pageXOffset - docEl.clientLeft,
top: rect.top + window.pageYOffset - docEl.clientTop,
width: element.offsetWidth,
height: element.offsetHeight
};
}
var links = getAllChildren(document.body, 'a');
links.forEach(function(link){
var offset_node = offset(node);
console.info(offset_node);
});

With jQuery:
$j('a').each( findOffset );
function findOffset()
{
alert
( 'x=' + $j(this).offset().left
+ ' y=' + $j(this).offset().top
+ ' width=' + $j(this).width()
+ ' height=' + $j(this).height()
);
}

Related

jQuery : Get All DOM elements come under the selected part (Rectangle) like zooming plugins of jQuery

I want all the DOM elements (which can be overlapped by others too) to be listed out which falls under the selection. The thing I tried giving me at a fixed coordinate (with overlapped ones) but I need it to give me for full rectangle.
https://jsfiddle.net/mantrig/3tqqy0gt/
var flag=0;
$("#enable-show").click(function(){
if(flag==0) {
$(document).bind('mousemove', function(e){
$('#tail').css({
left: e.pageX - 80,
top: e.pageY-50,
});
var $elements = GetAllElementsAt( e.pageX , e.pageY);
var html="";
$elements.each(function() {
html += $(this)[0].id + "<br />";
$("#result").html(html);
});
$("#tail").show();
});
flag++;
}
else {
$(document).bind('mousemove', function(e){
$("#tail").hide();
});
flag=0;
}
});
function GetAllElementsAt(x, y) {
var $elements = $("body *").map(function() {
var $this = $(this);
var offset = $this.offset();
var l = offset.left;
var t = offset.top;
var h = $this.height();
var w = $this.width();
var maxx = l + w;
var maxy = t + h;
$("ul").append("<li>" + $this[0].id + " (" + $this[0].tagName + ")" + " [l:=" + l + ",t:=" + t + ",h:=" + h + ",w:=" + w + ",maxx:=" + maxx + ",maxy:=" + maxy + "]</li>");
return (y <= maxy && y >= t) && (x <= maxx && x >= l) ? $this : null;
});
return $elements;
}
Can anyone help with it?

Calculating positioning of the parent Div

Hi i want to calculate the position of the Div. Pardon me if i am not able to explain it properly but i will try to explain everything in the simplest way. I am creating sidepanel ad and to place the panels i want the position of the width. When i upload the script on my server then i get a small script which we place on the publisher website and where our script runs inside the iframe. I want to get the position of the div which has a class 'content'. Here is the screen shot.
in the above screenshot the yellow highlighted script is calculating the position of the div class="content" which is in red box. My code was working fine but on the publisher site it was not working fine and i was only able to get only two Divs whose id is like ebDiv..... (these divs are above the yellow highlighted js).
Then i found out to read the parentDiv in order to get the content positions.
i wrote this code.
var parentDoc = window;
while (parentDoc !== parentDoc.parent) {
parentDoc = parentDoc.parent;
}
parentDoc = parentDoc.document;
var parentDiv = parentDoc.getElementsByTagName('div');
var divs = [];
for (var i = 0; i < parentDiv.length; i++) {
if (parentDiv[i].className == "content") {
alert(parentDiv[i].offsetWidth);
alert(parentDiv[i].offsetLeft);
}
The width is calcuated as 1010 which is fine but i am just missing left positioning which i am getting using parentDiv[i].offsetLeft is 2.
Above the screenshot has width 1010 which is fine but left positioning is not correct.
i had this code to calculate the width.
function ReadDivPos(selector) {
var _divPos = "";
$(selector).each(function() {
var p = $(this).offset();
var w = $(this).width();
console.log("Top " + p.top) //top
console.log("left " + p.left) //left
console.log("right " + p.left + w) //right
console.log("offsetWidth " + w); //width
_divPos += "Left " + p.left + ",Width " + w + ",Avail Width " + window.screen.availWidth + ",Right " + (p.left + w) + "\\n";
});
return _divPos;
}
console.log(ReadDivPos(".content"));
when i am using the same code to calculate the positioning then it is not working .
var parentDoc = window;
while (parentDoc !== parentDoc.parent) {
parentDoc = parentDoc.parent;
}
parentDoc = parentDoc.document;
var parentDiv = parentDoc.getElementsByTagName('div');
var divs = [];
for (var i = 0; i < parentDiv.length; i++) {
if (parentDiv[i].className == "content") {
$(parentDiv[i]).each(function() {
var p = $(this).offset();
var w = $(this).width();
console.log("Top " + p.top) //top
console.log("left " + p.left) //left
console.log("right " + p.left + w) //right
console.log("offsetWidth " + w); //width
_divPos += "Left " + p.left + ",Width " + w + ",Avail Width " + window.screen.availWidth + ",Right " + (p.left + w) + "\\n";
}
}
Can someone me explain me how to fix this. Jquery/Javascript anythingwould be fine. I am not good in the frontend things so i am sorry if i could not explain it better. Thanks in advance
Here is a function used to get the position on the page of an element:
function getPosition(element) {
var xPosition = 0;
var yPosition = 0;
while (element) {
xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
element = element.offsetParent;
}
return { x: xPosition, y: yPosition };
}
Used like this:
var pos = getPosition(element);
var x = pos["x"];
var y = pos["y"];
I'm not sure if this is exactly what you need, but if not maybe you can tweak it to fit your situation

javascript drag and drop, dragging elements around the page is inaccurite

so I have a canvas that takes up 100% of the page size and ontop of this canvas are other html elements. I want to make it so any element that has the class game-gui can be dragged round the screen (so users can position them where they want).
the js fiddle for this looks like this:
http://jsfiddle.net/VYJCj/2/
the code for this can be seen below:
$('.game-gui').each(function(i, obj) {
$(obj).on('dragstart', function(event){
var left = parseInt($(obj).css("left"), 10);
var top = parseInt($(obj).css("top"), 10);
event.originalEvent.dataTransfer.effectAllowed = 'move';
var str = (left - event.originalEvent.clientX) + ',' + (top - event.originalEvent.clientY)+ ',' + event.target.id;
event.originalEvent.dataTransfer.setData("text/plain", str);
});
});
this.canvas = $('#game_canvas');
this.canvas.bind('drop', function(event){
event.stopPropagation();
event.preventDefault();
var offset = event.originalEvent.dataTransfer.getData("text/plain").split(',');
console.log(offset);
var obj = $('#' + offset[2]);
var clientX = event.originalEvent.clientX || 0;
var clientY = event.originalEvent.clientY || 0 ;
obj.css('left', ( clientX+ parseInt(offset[0],10)) + 'px');
obj.css('top', ( clientY + parseInt(offset[1],10)) + 'px');
return false;
});
this.canvas.bind('dragover', function(event){
event.preventDefault();
event.originalEvent.dataTransfer.dropEffect = 'move';
return false;
});
as you will be able to see from the demo you can move the elements around the page however they move into different positions then they should! would anyone be able to help me on the matter?

How to remove selected image on a div when you click on it?

I am fairly new to Javascript and would like to create a div whereby it allows a person to define points on it by clicking on the area within the div. An image will be added to represent the point clicked. Thereafter, if the person wants to remove this point, upon clicking on the image, it should be remove.
I have done the part whereby it allows a person to define the points based on a minor modification to an existing fiddle: http://jsfiddle.net/uKkRh/1/
Reference: jquery how to add pin to image and save the position to SQL
I also manage to remove all the images by click on the button.
However, I am still short of how to remove the image from the div when the person clicks on the image.
I have tried the following:
$('#container >img').click(function() {
var selectedImg = $(this);
selectedImg.remove();
return;
});
but it works itermitently.
Please see my JSfiddle for my sample. http://jsfiddle.net/WindSaviour/rUNsJ/19/
var point = [];
var id = 0;
$(document).ready(function() {
var output = $('#container');
$("#container").click(function(e) {
e.preventDefault();
var isPointPresent = false;
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
console.log("Mouse Click Pos (x=" + x + ", y=" + y + ")");
for(var i=0; i< point.length; i++) {
if(x >= point[i].min_x && x<=point[i].max_x) {
if(y >= point[i].min_y && y<=point[i].max_y) {
isPointPresent = true;
point.splice(i,1);
break;
}
}
}
point[point.length] = { "x-pos": x, "y-pos":y, "min_x": x-25, "max_x": x+25, "min_y": y-83, "max_y": y};
if(isPointPresent) {
$('#container >img').click(function() {
var selectedImg = $(this);
selectedImg.remove();
return;
});
}
var img = $('<img>');
var left = x-25;
var top = y-83;
console.log("Img Start Pos (x=" + left + ", y=" + top + ")");
img.css('top', top);
img.css('left', left);
img.attr('src', 'http://www.clker.com/cliparts/P/w/G/0/N/o/google-map-th.png');
img.attr('id', id);
img.appendTo('#container');
/*
*/
id++;
})
});
$('#remove').click(function() {
$('#container > img').remove();
});
Try this http://jsfiddle.net/uKkRh/635/, but you need a newer verion of jQuery
$('#container').on('click', 'img', function (e) {
e.stopPropagation();
$(this).remove();
});

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