How to get the lower co-ordinate of images in html - javascript

I have a image and it is inside a div. I want to know what would be the lower co-ordinates for the image. Like if it a rectangle with corners A,B,C and D with A as the bottom left corner I want to get the co-ordinates of that. Could you let me know how I could achieve that using JavaScript or jQuery.

You can do this with JQuery position() and return left and top
var pos = $('img').position();
$('.result').append('(x: ' + pos.left + ', y: ' + pos.top + ')');
div {
width: 200px;
height: 200px;
position: relative;
border: 1px solid black;
}
img {
position: absolute;
left: 40px;
top: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img src="http://placehold.it/50x50">
</div>
<span class="result"></span>

The best solution would be to use getBoundingClientRect()
var image = $( "img" );
var imageBounds = image.get(0).getBoundingClientRect();
var imageLeft = imageBounds.left;
var imageBottom = imageBounds.bottom;
Fiddle
But you could also use jQuery's .position() to get the top and left coordinates then to calculate the bottom and right position just add .height() or .width()
var image = $( "img" );
var imagePosition = image.position();
var imageHeight = image.height();
var imageLeft = imagePosition.left;
var imageBottom = imagePosition.top + imageHeight;
Fiddle
or without using jQuery:
var image = document.getElementById("image");
var imageBounds = image.getBoundingClientRect();
var imageLeft = imageBounds.left;
var imageBottom = imageBounds.bottom;
Fiddle

You can use .position() to get left and top coordinates(top left corner).
to get the bottom left corner just add image height to top coordinate.
$(window).load(function(){ //to make sure all images are loaded
console.log($('img').position().left);
console.log($('img').position().top + $('img').height());
});
div { padding: 30px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><img src="http://placehold.it/350x150"></div>

Here is the demo on codepen: http://codepen.io/ssh33/pen/AXdVER
Waits for the image to download to get the width and height and calls GetCoordinates().
If the image has been previously cached $("#image").load() will never fire. In this case $(window).load() will call GetCoordinates() instead. GetCoordinates() checks for non-numeric width/height and retrieves it if necessary.
Recalculates on window resize.
var img_width, img_height, x, y;
$("#image").load(function() {
img_width = this.width;
img_height = this.height;
});
var GetCoordinates = function(){
if (isNaN(img_width) || isNaN(img_height)){
img_width = $("#image").width();
img_height = $("#image").height();
}
var img_left = $("#image").offset().left;
x = img_width + img_left;
var img_top = $("#image").offset().top;
y = img_height + img_top;
}
$(window).load(function() {
GetCoordinates();
});
$(window).resize(function() {
GetCoordinates();
});

Related

Draggable jQuery Restriction

I'm trying to scroll an image by dragging my cursor. I'm using the Draggable jQuery library but I'm having a problem.
I need to determine the limit of the image so that I can block the drag to avoid showing white space.
Anyone can help me with that?
jsfiddle
<div style="width:100%;height:100%;" id="parent">
<img src="http://cdn.wallpapersafari.com/10/37/Aim58J.jpg" id="draggable"/>
$( "#draggable" ).draggable({
axis: 'x,y',
cursor: "crosshair",
});
If you need scrolling by dragging, do not use dragging. Use simple mouse move instead. Look at the example below. In this case you can scroll any content inside your container.
Hope it would help.
UPDATED:
If you need dragging of some background element, you should to drag it by mousemove and calculate visible area according to container size.
So, in few words - Drag image left till its width minus left offset is bigger than container(window) width, and so on for right, top and down offsets.
// Main script
function run() {
var $image = $('#draggable');
var $window = $(window);
var isStarted = false;
var cursorInitialPosition = {left: 0, top: 0};
var imageInitialPosition = {left: 0, top: 0};
var imageSize = {width: $image.width(), height: $image.height()};
// stop dragging
var stop = function() {
isStarted = false;
$window.unbind('mousemove', update);
};
// update image position
var update = function(event) {
// size of container (window in our case)
var containerSize = {width: $window.width(), height: $window.height()};
var left = imageInitialPosition.left + (event.pageX - cursorInitialPosition.left);
var top = imageInitialPosition.top + (event.pageY - cursorInitialPosition.top);
// don't allow dragging too left or right
if (left <= 0 && imageSize.width + left >= containerSize.width) {
$image.css('left', left);
}
// don't allow dragging too top or down
if (top <= 0 && imageSize.height + top >= containerSize.height) {
$image.css('top', top);
}
};
$window.mousedown(function(event){
var position = $image.position();
cursorInitialPosition.left = event.pageX;
cursorInitialPosition.top = event.pageY;
imageInitialPosition.left = position.left;
imageInitialPosition.top = position.top;
$(window).mousemove(update);
});
$window.mouseout(stop);
$window.mouseup(stop);
}
$(function(){
// wait for image loading because we need it size
var image = new Image;
image.onload = run;
image.src = "http://cdn.wallpapersafari.com/10/37/Aim58J.jpg";
});
https://jsfiddle.net/2hxz49bj/5/

Positioning image in the page with OnMouseOver function

I have a function that onmouseover load a javascript function which is
function imgEnlarge(val) {
var imageFile = getVal(arrayFile, {
'id': val
}, 'picture');
var imagePath = 'admin/img/' + imageFile;
document.getElementById("imgDisplay").innerHTML = '<img src="' + imagePath + '" style="width:800px;height600px">';
} //end enlarge function
.imgDisplay {
top: 50;
left: 200;
position: absolute;
z - index: 999;
width: 600 px;
height: 500 px;
}
The problem is when i scroll down to e.g middle of the page, the display is still at the "top of the page" as I can see the bottom of the image appearing on the div.
I have an empty div at the top of my site that is having the id of imgDisplay
How do I fix the code such that onmouseover, the picture display will at the current screen X,Y instead of top: and left: (from the top of page)
You can simply set the position of your image as fixed and top and left properties to 0.
Here is a javascript solution:
var image = document.getElementById('imgDisplay');
image.addEventListener('mouseover', function(){
this.style.position = "fixed";
this.style.top = 0;
this.style.left = 0;
});

How do I find the center of an image, and place another image on top of it?

HTML:
<img src="img/image1.jpg" id = "image1" style="width: 100%;" allign = "center">
JavaScript:
var image1 = document.getElementById("image1");
How would I get the center of this given image, and then place another image which has an absolute position on top of it dead center?
You can use getBoundingClientRect() on the images to find their exact position and calculate using those values. This method will take into consideration the CSS size as well as scroll position etc.
The second image is placed below using fixed position, for demo, but you can use a parent div set to relative and place the image inside that using absolute etc.
Example
function centerImages() {
var image1 = document.getElementById("image1");
var rect1 = image1.getBoundingClientRect();
var cx = rect1.left + rect1.width * 0.5; // find center of first image
var cy = rect1.top + rect1.height * 0.5;
var image2 = document.getElementById("image2");
var rect2 = image2.getBoundingClientRect();
var x = cx - rect2.width * 0.5; // use center of first, subtract second
var y = cy - rect2.height * 0.5;
image2.style.cssText = "position:fixed;left:" + x + "px; top:" + y + "px";
}
window.onload = window.onresize = window.onscroll = centerImages;
<img src="http://i.stack.imgur.com/UDTPI.gif" id="image1" style="width: 100%;">
<img src="http://i.stack.imgur.com/fk5Js.gif" id="image2">
http://jsfiddle.net/33ra14az/1/ here's a way I came up with using JS + resize event for responsive.
function setImg() {
var img1 = document.getElementById('image1'),
img2 = document.getElementById('image2'),
offtop = ((img1.offsetHeight/2)-(img2.offsetHeight/2)),
offleft = ((img1.offsetWidth/2)-(img2.offsetWidth/2));
img2.style.top = offtop + "px";
img2.style.left = offleft + "px";
}
window.load = setImg();
window.addEventListener('resize',setImg);
well you can try this :
$(document).ready(function() {
var top=($("#image1").height()/2)-($("#image2").height()/2);
var left=($("#image1").width()/2)-($("#image2").width()/2);
$("#image2").css('left',left+'px');
$("#image2").css('top',top+'px');
});
and the css is simple:
#image2{
position: absolute;
display:block;
width:100px;
height:100px;
}
and this is the html code:
<img src="http://doc.jsfiddle.net/_downloads/jsfiddle-logo.png" id = "image1" style="width: 100%;" allign = "center">
<img src="http://www.hakandemirel.com.tr/blog/wp-content/uploads/jsfiddle.png" id ="image2">
this is demo:
http://jsfiddle.net/yysdged6/22/

How to get the distance from the top for an element?

I want to know how to use JavaScript to get the distance of an element from the top of the page not the parent element.
http://jsfiddle.net/yZGSt/1/
var elDistanceToTop = window.pageYOffset + el.getBoundingClientRect().top
In my experience document.body.scrollTop doesn't always return the current scroll position (for example if the scrolling actually happens on a different element).
offsetTop only looks at the element's parent. Just loop through parent nodes until you run out of parents and add up their offsets.
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 };
}
UPDATE: This answer has some problems, values will have tiny differences compare to what it should be and will not work correctly in some cases.
Check #eeglbalazs's answer, which is accurate.
Here is some interesting code for you :)
window.addEventListener('load', function() {
//get the element
var elem = document.getElementById('test');
//get the distance scrolled on body (by default can be changed)
var distanceScrolled = document.body.scrollTop;
//create viewport offset object
var elemRect = elem.getBoundingClientRect();
//get the offset from the element to the viewport
var elemViewportOffset = elemRect.top;
//add them together
var totalOffset = distanceScrolled + elemViewportOffset;
//log it, (look at the top of this example snippet)
document.getElementById('log').innerHTML = totalOffset;
});
#test {
width: 100px;
height: 100px;
background: red;
margin-top: 100vh;
}
#log {
position: fixed;
top: 0;
left: 0;
display: table;
background: #333;
color: #fff;
}
html,
body {
height: 2000px;
height: 200vh;
}
<div id="log"></div>
<div id="test"></div>
Use offsetTop
document.getElementById("foo").offsetTop
Demo
offsetTop doesn’t get the distance to the top of the page, but rather to the top of the closest parent element that has a specified position.
You can use a simple technique that adds up the offsetTop of all the parent element of the element you are interested in to get the distance.
// Our element
var elem = document.querySelector('#some-element');
// Set our distance placeholder
var distance = 0;
// Loop up the dom
do {
// Increase our distance counter
distance += elem.offsetTop;
// Set the element to it's parent
elem = elem.offsetParent;
} while (elem);
distance = distance < 0 ? 0 : distance;
Original code from https://gomakethings.com/how-to-get-an-elements-distance-from-the-top-of-the-page-with-vanilla-javascript/
This oneliner seems to work nice
document.getElementById("el").getBoundingClientRect().top + window.scrollY
your fiddle updated
var distanceTop = element.getBoundingClientRect().top;
For details vist a link:
https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
**For anchor links (href="/#about") to anchor <div id="about"> read part 3.
1 (distance_from_top)
Less than 30 seconds solution (Two lines of code "hello world"):
get your element:
var element = document.getElementById("hello");
Get getBoundingClientRect ();
The Element.getBoundingClientRect() method returns the size of an
element and its position relative to the viewport. https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
var rect = element.getBoundingClientRect();
Return object:
Dot notation top
var distance_from_top = rect.top; /* 1007.9971313476562 */
Thats it.
2 (window.scrollTo)
StackOverflow nightmare 2 - set scroll position to this value
Again "hello world" (8,000 answers out there - 7,999 not working or to complex).
https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo
window.scrollTo({
top: element.getBoundingClientRect().top,
behavior: 'smooth'
});
Add offset value to top if you want (For sticky navbars).
"Hello World" code snippet (Get distance from top viewport + click to scrollTo)
var element = document.getElementById("hello");
var rect = element.getBoundingClientRect();
var distance_from_top = rect.top; /* 50px */
console.log(distance_from_top);
function scrollTovView(){
window.scrollTo({
top: distance_from_top,
behavior: 'smooth'
});
}
div{
text-align:center;
border: 1px solid lightgray;
}
<button onclick="scrollTovView()">scrollTo to red DIV</button>
<div style="height: 50px;">50px height</div>
<div id="hello" style="width: 500px; height: 500px; background: red;"></div>
3 (scrollTo & anchors)
scrollTo "conflict" with main anchor navbars
This trick is very buggy if, for example, you use this URL:
www.mysite/about#hello
to
<div id="hello">hello</div>
top is 0 or buggy (The HTML moves to hello section).
window.scrollTo({
top: element.getBoundingClientRect().top,
behavior: 'smooth'
});
For this code to work you should add:
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
Basic example her:
https://www.w3schools.com/howto/howto_css_smooth_scroll.asp
Although it is quite an old discussion, but this works pretty well on chrome / firefox / safari browsers:
window.addEventListener('scroll', function() {
var someDiv = document.getElementById('someDiv');
var distanceToTop = someDiv.getBoundingClientRect().top;
});
Check it out on JSFiddle
scroll to element's top position;
var rect = element.getBoundingClientRect();
var offsetTop = window.pageYOffset + rect.top - rect.height;
document.getElementById("id").offsetTop
(SOURCE : Determine distance from the top of a div to top of window with javascript )
<script type="text/javascript">
var myyElement = document.getElementById("myyy_bar"); //your element
var EnableConsoleLOGS = true; //to check the results in Browser's Inspector(Console), whenever you are scrolling
// ==============================================
window.addEventListener('scroll', function (evt) {
var Positionsss = GetTopLeft ();
if (EnableConsoleLOGS) { console.log(Positionsss); }
});
function GetOffset (object, offset) {
if (!object) return;
offset.x += object.offsetLeft; offset.y += object.offsetTop;
GetOffset (object.offsetParent, offset);
}
function GetScrolled (object, scrolled) {
if (!object) return;
scrolled.x += object.scrollLeft; scrolled.y += object.scrollTop;
if (object.tagName.toLowerCase () != "html") { GetScrolled (object.parentNode, scrolled); }
}
function GetTopLeft () {
var offset = {x : 0, y : 0}; GetOffset (myyElement, offset);
var scrolled = {x : 0, y : 0}; GetScrolled (myyElement.parentNode, scrolled);
var posX = offset.x - scrolled.x; var posY = offset.y - scrolled.y;
return {lefttt: posX , toppp: posY };
}
// ==============================================
</script>
This function returns distance from top of the page, even if your window is scrolled. It can be used in event listeners.
const getElementYOffset = (element) => {
const scrollOnWindow =
window.pageYOffset !== undefined
? window.pageYOffset
: (document.documentElement || document.body.parentNode || document.body)
.scrollTop;
const rect = element.getBoundingClientRect();
let distanceFromTopOfPage = rect.top;
if (scrollOnWindow !== 0) {
distanceFromTopOfPage = rect.top + scrollOnWindow;
}
return distanceFromTopOfPage;
};
You only need this line
document.getElementById("el").getBoundingClientRect().top
in which "el" is the element.
Since window.pageYOffset is a legacy alias of window.scrollY, eeglbalazs answer can be improved to:
const elDistanceToTop = window.scrollY + el.getBoundingClientRect().top;
Using jQuery's offset() method:
$(element).offset().top
Example: http://jsfiddle.net/yZGSt/3/

How to position a DIV in a specific coordinates?

I want to position a DIV in a specific coordinates ? How can I do that using Javascript ?
Script its left and top properties as the number of pixels from the left edge and top edge respectively. It must have position: absolute;
var d = document.getElementById('yourDivId');
d.style.position = "absolute";
d.style.left = x_pos+'px';
d.style.top = y_pos+'px';
Or do it as a function so you can attach it to an event like onmousedown
function placeDiv(x_pos, y_pos) {
var d = document.getElementById('yourDivId');
d.style.position = "absolute";
d.style.left = x_pos+'px';
d.style.top = y_pos+'px';
}
You don't have to use Javascript to do this.
Using plain-old css:
div.blah {
position:absolute;
top: 0; /*[wherever you want it]*/
left:0; /*[wherever you want it]*/
}
If you feel you must use javascript, or are trying to do this dynamically
Using JQuery, this affects all divs of class "blah":
var blahclass = $('.blah');
blahclass.css('position', 'absolute');
blahclass.css('top', 0); //or wherever you want it
blahclass.css('left', 0); //or wherever you want it
Alternatively, if you must use regular old-javascript you can grab by id
var domElement = document.getElementById('myElement');// don't go to to DOM every time you need it. Instead store in a variable and manipulate.
domElement.style.position = "absolute";
domElement.style.top = 0; //or whatever
domElement.style.left = 0; // or whatever
well it depends if all you want is to position a div and then nothing else, you don't need to use java script for that. You can achieve this by CSS only. What matters is relative to what container you want to position your div, if you want to position it relative to document body then your div must be positioned absolute and its container must not be positioned relatively or absolutely, in that case your div will be positioned relative to the container.
Otherwise with Jquery if you want to position an element relative to document you can use offset() method.
$(".mydiv").offset({ top: 10, left: 30 });
if relative to offset parent position the parent relative or absolute. then use following...
var pos = $('.parent').offset();
var top = pos.top + 'no of pixel you want to give the mydiv from top relative to parent';
var left = pos.left + 'no of pixel you want to give the mydiv from left relative to parent';
$('.mydiv').css({
position:'absolute',
top:top,
left:left
});
Here is a properly described article and also a sample with code.
JS coordinates
As per requirement. below is code which is posted at last in that article.
Need to call getOffset function and pass html element which returns its top and left values.
function getOffsetSum(elem) {
var top=0, left=0
while(elem) {
top = top + parseInt(elem.offsetTop)
left = left + parseInt(elem.offsetLeft)
elem = elem.offsetParent
}
return {top: top, left: left}
}
function getOffsetRect(elem) {
var box = elem.getBoundingClientRect()
var body = document.body
var docElem = document.documentElement
var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop
var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft
var clientTop = docElem.clientTop || body.clientTop || 0
var clientLeft = docElem.clientLeft || body.clientLeft || 0
var top = box.top + scrollTop - clientTop
var left = box.left + scrollLeft - clientLeft
return { top: Math.round(top), left: Math.round(left) }
}
function getOffset(elem) {
if (elem.getBoundingClientRect) {
return getOffsetRect(elem)
} else {
return getOffsetSum(elem)
}
}
You can also use position fixed css property.
<!-- html code -->
<div class="box" id="myElement"></div>
/* css code */
.box {
position: fixed;
}
// js code
document.getElementById('myElement').style.top = 0; //or whatever
document.getElementById('myElement').style.left = 0; // or whatever
To set the content of a div you can use the following:
document.getElementById(id).style.top = "0px";
document.getElementById(id).style.left = "0px";
Exists other good alternatives in jQuery
I cribbed this and added the 'px';
Works very well.
function getOffset(el) {
el = el.getBoundingClientRect();
return {
left: (el.right + window.scrollX ) +'px',
top: (el.top + window.scrollY ) +'px'
}
}
to call: //Gets it to the right side
el.style.top = getOffset(othis).top ;
el.style.left = getOffset(othis).left ;

Categories

Resources