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
Related
This is how I get the click position when clicking on an image to do some image transformation. But my problem is, that the image has the CSS attribute max-width: 1000px. So the code works only for images which are smaller. For larger images the position result is not the real pixel which was clicked on.
My question is, if it is possible to calculate the correct click position for the natural sized image. An alternative would be to set some data attributes with the real image size like data-width: '1200px' and data-height: '1000px'. But still I have to do some calculation.
parentPosition = getPosition(event.currentTarget),
x = event.clientX - parentPosition.x,
y = event.clientY - parentPosition.y;
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 };
}
If you know natural size and current size, i think you can just do this:
naturalClickPosX = (naturalWidth / currentWidth) * currentClickPosX;
naturalClickPosY = (naturalHeight / currentHeight) * currentClickPosY;
Have a look at this JSFiddle
HTML
<img src="http://placehold.it/1200x1000" width="1000">
JavaScript
$('img').on("click", function(e){
var $img = $(this);
var currentClickPosX = e.pageX - $img.offset().left;
var currentClickPosY = e.pageY - $img.offset().top;
var currentWidth = $img.width();
var currentHeight = $img.height();
var naturalWidth = this.naturalWidth;
var naturalHeight = this.naturalHeight;
var naturalClickPosX = ((naturalWidth / currentWidth) * currentClickPosX).toFixed(0);
var naturalClickPosY = ((naturalHeight / currentHeight) * currentClickPosY).toFixed(0);
alert("Current X: " + currentClickPosX + " Current Y: " + currentClickPosY +
"\r\nNatural X: " + naturalClickPosX + " Natural Y: " + naturalClickPosY);
});
try this , will work on all sizes
$('.img-coordinate').click(function(e){
var parentOffset = $(e.target).parent().offset();
// here the X and Y on Click
X = e.pageX - $(e.target).offset().left;
Y = e.pageY - $(e.target).offset().top;
alert(X + ' , ' + Y );
});
working fiddel : https://jsfiddle.net/h09kfsoo/
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?
I am working on a jQuery tooltip module for personal use. In my code I'm using jQuery's mousemove and mouseout functions in order to generate the tooltip. However, when I move my mouse over the element it hits the if statement in the build function and says that the tooltip should be there even though I can see in Firebug and in the Chrome Dev Tools that it's not.
$.fn.tooltip = function(userOptions)
{
var defaultOptions = {
position: '',
follow: true
};
var options = $.extend(defaultOptions, userOptions);
$(this).mouseenter(function()
{
var title = $(this).data('title');
build(title, options.position, options.follow);
var top, left;
var tooltip = $('#tooltip');
if (tooltip.hasClass('top'))
{
top = $(this).offset().top - ($(this).height() * 2) - 10;
left = $(this).offset().left;
}
else if (tooltip.hasClass('right'))
{
top = $(this).offset().top - ($(this).height() / 2);
left = $(this).offset().left + tooltip.width();
}
else if (tooltip.hasClass('bottom'))
{
top = $(this).offset().top + $(this).height() + 10;
left = $(this).offset().left;
}
else if (tooltip.hasClass('left'))
{
top = $(this).offset().top - ($(this).height() / 2);
left = $(this).offset().left - (tooltip.width() * 1.5);
}
tooltip.css('top', top).css('left', left).show();
});
$(this).mousemove(function(e)
{
if (options.position === "" || options.position === undefined || options.follow === true)
{
var title = $(this).data('title');
build(title, options.position, options.follow);
var top = e.pageY + 25;
var left = e.pageX + 10;
$('#tooltip').css('top', top).css('left', left).show();
}
});
$(this).mouseout(function()
{
$('#tooltip').hide();
});
function build(title, position, follow)
{
if ($('#tooltip'))
{
console.log("The tooltiop should be on the page.");
$('#tooltip-content > p').text = title;
}
else
{
console.log("Position is: " + position);
var markup = '<div id="tooltip" class=' + position + '">';
markup += '<div id="tooltip-content">';
markup += '<p>' + title + '</p>';
markup += '<span id="tooltip-arrow"></span>';
markup += '</div>';
markup += '</div>';
$('body').append(markup);
}
}
};
The original goal was to create the tooltip the first time the user moves over the element and then when the mouse moves away I wanted to hide the tooltip and move it out of the way until it's needed again. That's why I'm checking to see if it exists in the build function. I know I'm overlooking something, I just can't figure out what it is. Any suggestions?
In build function change the check in the if like:
if ($('#tooltip').lenght) {
that will return false if #tooltip is not yet appended to body and true if it is.
The $('#tooltip') will return always a jQuery object thus it will never be false but its length will be 0, thus false, if the tooltip element is not yet added to the body.
jsFiddle
Regards.
Ok, so I am trying to use jQuery to get the innerWidth() of an element #preview. I want to create a conditional that says IF x offset LEFT + #preview width is greater than page width, give it style right: z where z = #preview width + xOffset.
I apologize my code below is a mess and the syntax for .css ("right", (rightFloat + xOffset) + "px") (line 125) is off, but that's part of my problem.
<script>
$(document).ready(function(){
//append "gallery" class to all items with "popup" class
imagePreview();
$(".popup").addClass("gallery");
});
//The overlay or pop-up effect
this.imagePreview = function() { /* CONFIG */
xOffset = 40;
yOffset = 40;
// these 2 variable determine popup's distance from the cursor
// you might want to adjust to get the right result
/* END CONFIG */
$("a.preview").click(function(e) {
return false;
});
$("a.preview").hover(function(e) {
this.t = this.title;
this.title = "";
var c = (this.t != "") ? "<br/>" + this.t : "";
var rightFloat = e.pageX + ("#preview").innerWidth;
$("body").append("<p id='preview'><img src='" + this.href + "' alt='Image preview' />" + c + "</p>");
$("#preview").hide().css("top", (e.pageY - yOffset) + "px").css("left", (e.pageX + xOffset) + "px").fadeIn("2000");
while ((left + 400) > window.innerWidth) {.css("right", (rightFloat + xOffset) + "px")
}
}, function() {
this.title = this.t;
$("#preview").remove();
});
$("a.preview").mousemove(function(e) {
var top = e.pageY - yOffset;
var left = e.pageX + xOffset;
var rightFloat = e.pageX + ("#preview").innerWidth;
//flips the image if it gets too close to the right side
while ((left + 400) > window.innerWidth) {.css("right", +(rightFlaot + xOffset) + "px")
}
$("#preview").css("top", top + "px").css("left", left + "px");
});
};
</script>
Try using http://api.jquery.com/offset/
if($('#preview').offset().right<0){
var right = parseInt($(window).width()) - e.pageX + xOffset;
$("#preview").css("top", top + "px").css("right", right + "px");
}else{
var left = e.pageX + xOffset;
$("#preview").css("top", top + "px").css("left", left + "px");
}
I made these fixes because I couldn't get your code to work in jsfiddle:
var xOffset = 40;
var yOffset = 40;
$("a.preview").bind('mouseover',function(e){
var rightFloat = parseFloat(e.pageX)+$("#preview").innerWidth();
var ptop = parseFloat(e.pageY) - yOffset;
var pleft = parseFloat(e.pageX) + xOffset;
$("#preview").css({"top":ptop + "px","left":pleft + "px"});
});
There's the fixes for the top half but I have no idea what you're trying to do with the bottom part (with the while loop). Can you explain what functionality you want?
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()
);
}