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 ;
Related
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/
Say I have a wrapper div with a overflow:hidden on it and a div inside that that spans far below the visible portion. How can I get the visible height of the internal div?
<div id="wrapper" style="overflow: hidden; height:400px;">
<div id="inner">
<!--Lots of content in here-->
</div>
<div>
Every method I try attempting to get the height of the inner div returns the complete height including the hidden parts, i.e. 2000px. I want to be able to get the height of only the visible portion, so 400px in this example case.
I know I could just get the height of the parentNode, but in production, the inner div might not be a first child. So there might be other divs separating them, and so the height of #inner would be 400 - whatever the offsets of the elements between it and #wrapper.
As basic algorithm this could work:
var offset = 0;
var node = document.getElementById("inner");
while (node.offsetParent && node.offsetParent.id != "wrapper")
{
offset += node.offsetTop;
node = node.offsetParent;
}
var visible = node.offsetHeight - offset;
But if you're doing these kinds of things, maybe you already use jQuery, which might be of service with its .height() and .offset() functions:
$("#wrapper").height()-
$("#inner").offset()['top']+
$("#wrapper").offset()['top'];
Quick algorithm that goes up the DOM tree looking at window.getComputedStyle for overflow: hidden
function visibleArea(node){
var o = {height: node.offsetHeight, width: node.offsetWidth}, // size
d = {y: (node.offsetTop || 0), x: (node.offsetLeft || 0), node: node.offsetParent}, // position
css, y, x;
while( null !== (node = node.parentNode) ){ // loop up through DOM
css = window.getComputedStyle(node);
if( css && css.overflow === 'hidden' ){ // if has style && overflow
y = node.offsetHeight - d.y; // calculate visible y
x = node.offsetWidth - d.x; // and x
if( node !== d.node ){
y = y + (node.offsetTop || 0); // using || 0 in case it doesn't have an offsetParent
x = x + (node.offsetLeft || 0);
}
if( y < o.height ) {
if( y < 0 ) o.height = 0;
else o.height = y;
}
if( x < o.width ) {
if( x < 0 ) o.width = 0;
else o.width = x;
}
return o; // return (modify if you want to loop up again)
}
if( node === d.node ){ // update offsets
d.y = d.y + (node.offsetTop || 0);
d.x = d.x + (node.offsetLeft || 0);
d.node = node.offsetParent;
}
}
return o; // return if no hidden
}
example fiddle (look at your console).
The only way I've found to do this in every circumstance, including when there's overflow, transform: translate()s are used, and there are other nested containers in between an element and the element that's hiding its overflow is to combine .getBoundingClientRect() with a reference to the ancestor that's hiding the element's overflow:
function getVisibleDimensions(node, referenceNode) {
referenceNode = referenceNode || node.parentNode;
var pos = node.getBoundingClientRect();
var referencePos = referenceNode.getBoundingClientRect();
return {
"width": Math.min(
node.clientWidth,
referencePos.left + referenceNode.clientWidth - pos.left,
node.clientWidth - (referencePos.left - pos.left)
),
"height": Math.min(
node.clientHeight,
referencePos.top + referenceNode.clientHeight - pos.top,
node.clientHeight - (referencePos.top - pos.top)
)
}
}
Demo.
If a reference node is not given, the parent node is assumed: Demo.
Note that this doesn't take into account whether or not an element is viewable in the viewport, just visible (not hidden due to overflow). If you need both, you can combine functionality with this answer. It also has no check of visibility: hidden, so if you need that you need to check the style.visibility property of the node and all its ancestors.
I think keeping a sibling next to it, calculating its scrollTop and the overflow element scrollTop and then subtracting it from the siblings scroolTop might work
The code below computes the visible portion of an element. By visible portion I mean the part that is visible in the window, but I think you can easily alter it to base the computation on an arbitrary container element.
function computeVisibleHeight ($t) {
var top = $t.position().top;
var windowHeight = $(window).height();
var scrollTop = $(window).scrollTop();
var height = $t.height();
if (top < scrollTop && height - scrollTop >= windowHeight) {
// first case: the top and the bottom of the element is outside of the window
return windowHeight;
} else if (top < scrollTop) {
// second: the top is outside of the viewport but the bottom is visible
return height - (scrollTop - top);
} else if (top > scrollTop && top + height < windowHeight) {
// the whole element is visible
return height;
} else {
// the top is visible but the bottom is outside of the viewport
return windowHeight - (top - scrollTop);
}
}
The code is using jquery.
I have table with few records and I need to show a popup box when the user mouses over a certain record.
I have created the popup box and set the message there. The only thing that's left is to set the coordinates of that box (<div id="popup"></div>) so that it's next to the element that triggers this box.
So I got the this of the tag I mouse over. Now how can I get its location on the window?
I tried this.offsetLeft and it's relative to parent. The element is inline so I don't know how to find it.
I using pure JavaScript and please don't suggest jQuery as I don't want to use it in this project.
var box = this.getBoundingClientRect();
alert( "y:" + box.top + "x:"+ box.left );
http://jsfiddle.net/hNShL/
To take scrolling into account:
var body = document.body,
html = document.documentElement,
scrollTop = window.pageYOffset || html.scrollTop || body.scrollTop || 0,
scrollLeft = window.pageXOffset || html.scrollLeft || body.scrollLeft || 0,
box = this.getBoundingClientRect(),
top = box.top + scrollTop,
left = box.left + scrollLeft;
alert( "y:" + top + "x:"+ left );
You could try recursively going through the element's offsetParents to get their offsetLeft values and add them to the element's own offsetLeft.
Something like this should do the trick:
function offsetLeftRelativeToPage(element) {
var offset = element.offsetLeft;
var offsetParent = element.offsetParent;
if (offsetParent != null) {
offset += offsetLeftRelativeToPage(offsetParent);
}
return offset;
}
var trigger = document.getElementById('trigger');
var popup = document.getElementById('popup');
trigger.onmouseover = function() {
var offsetLeft = offsetLeftRelativeToPage(this);
popup.style.left = offsetLeft;
}
JSFiddle demo: jsfiddle.net/e6vWV/
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 do I determine the distance between the very top of a div to the top of the current screen? I just want the pixel distance to the top of the current screen, not the top of the document. I've tried a few things like .offset() and .offsetHeight, but I just can't wrap my brain around it. Thanks!
You can use .offset() to get the offset compared to the document element and then use the scrollTop property of the window element to find how far down the page the user has scrolled:
var scrollTop = $(window).scrollTop(),
elementOffset = $('#my-element').offset().top,
distance = (elementOffset - scrollTop);
The distance variable now holds the distance from the top of the #my-element element and the top-fold.
Here is a demo: http://jsfiddle.net/Rxs2m/
Note that negative values mean that the element is above the top-fold.
Vanilla:
window.addEventListener('scroll', function(ev) {
var someDiv = document.getElementById('someDiv');
var distanceToTop = someDiv.getBoundingClientRect().top;
console.log(distanceToTop);
});
Open your browser console and scroll your page to see the distance.
This can be achieved purely with JavaScript.
I see the answer I wanted to write has been answered by lynx in comments to the question.
But I'm going to write answer anyway because just like me, people sometimes forget to read the comments.
So, if you just want to get an element's distance (in Pixels) from the top of your screen window, here is what you need to do:
// Fetch the element
var el = document.getElementById("someElement");
use getBoundingClientRect()
// Use the 'top' property of 'getBoundingClientRect()' to get the distance from top
var distanceFromTop = el.getBoundingClientRect().top;
Thats it!
Hope this helps someone :)
I used this:
myElement = document.getElemenById("xyz");
Get_Offset_From_Start ( myElement ); // returns positions from website's start position
Get_Offset_From_CurrentView ( myElement ); // returns positions from current scrolled view's TOP and LEFT
code:
function Get_Offset_From_Start (object, offset) {
offset = offset || {x : 0, y : 0};
offset.x += object.offsetLeft; offset.y += object.offsetTop;
if(object.offsetParent) {
offset = Get_Offset_From_Start (object.offsetParent, offset);
}
return offset;
}
function Get_Offset_From_CurrentView (myElement) {
if (!myElement) return;
var offset = Get_Offset_From_Start (myElement);
var scrolled = GetScrolled (myElement.parentNode);
var posX = offset.x - scrolled.x; var posY = offset.y - scrolled.y;
return {lefttt: posX , toppp: posY };
}
//helper
function GetScrolled (object, scrolled) {
scrolled = scrolled || {x : 0, y : 0};
scrolled.x += object.scrollLeft; scrolled.y += object.scrollTop;
if (object.tagName.toLowerCase () != "html" && object.parentNode) { scrolled=GetScrolled (object.parentNode, scrolled); }
return scrolled;
}
/*
// live monitoring
window.addEventListener('scroll', function (evt) {
var Positionsss = Get_Offset_From_CurrentView(myElement);
console.log(Positionsss);
});
*/
I used this function to detect if the element is visible in view port
Code:
const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);
$(window).scroll(function(){
var scrollTop = $(window).scrollTop(),
elementOffset = $('.for-scroll').offset().top,
distance = (elementOffset - scrollTop);
if(distance < vh){
console.log('in view');
}
else{
console.log('not in view');
}
});