Save a specific BoundingClientRect? - javascript

I'm using getBoundingClientRect to change an elements position to absolute without changing it's position:
style.position = 'absolute'
style.top = container.getBoundingClientRect().top
style.left = container.getBoundingClientRect().left
style.width = container.offsetWidth
I do this to later transition the element to fullscreen, like this:
style.top = 0
style.left = 0
style.width = '100%'
style.height = '100%'
style.transitionProperty = 'top, left, width, height'
style.transitionDuration = '.2s'
Style is a javascript object that gets converted to css-properties.
Later on I want to close the full-screen-thing and revert the element back to it's original size. I would like to save the values from getBoundingClientRect as they are at the first transition. Can this be done?

Yes, it can be done. Like this:
var bcr = container.getBoundingClientRect();
style.width = '100%';
// later
style.width = bcr.width;
var el = document.querySelector('div');
var bcr = null;
document.querySelector('button').addEventListener('click', function() {
if (bcr) { // Currently fullscreen
el.style.position = '';
el.style.top = bcr.top + 'px';
el.style.left = bcr.left + 'px';
el.style.width = bcr.width + 'px';
el.style.height = bcr.height + 'px';
bcr = null;
} else {
bcr = el.getBoundingClientRect();
el.style.position = 'absolute';
el.style.top = el.style.left = 0;
el.style.width = el.style.height = '100%';
}
});
div {
background: yellow;
height: 100px;
width: 300px;
}
<div>
<button>Toggle fullscreen</button>
</div>
That said, most probably you don't need it, because just assigning the styles to the empty string will do the trick.

Related

When to use offsetHeight, clientHeight and scrollHeight and how to find we reached bottom of page?

What's the difference between offsetHeight, clientHeight and scrollHeight ?
Also, how to find that we reached bottom of the page considering that page is dynamically loaded(lazy loading) as we scroll down ?
offsetHeight:
Returns height of an element in px unit. Includes height of padding, scrollBar and border but NOT margin
clientHeight:
Returns height of an element in px unit. Includes padding but NOT scrollBar, border and margin
scrollHeight:
Returns height of an element in px unit. Includes padding, scrollBar, border and margin.
Same holds for Width in clientWidth, offsetWidth and scrollWidth
Here is an fiddle:
function whatis(propType)
{
var mainDiv = document.getElementById("MainDIV");
if(window.sampleDiv==null){
var div = document.createElement("div");
window.sampleDiv = div;
}
div = window.sampleDiv;
var propTypeWidth = propType.toLowerCase()+"Width";
var propTypeHeight = propType+"Height";
var computedStyle = window.getComputedStyle(mainDiv, null);
var borderLeftWidth = computedStyle.getPropertyValue("border-left-width");
var borderTopWidth = computedStyle.getPropertyValue("border-top-width");
div.style.position = "absolute";
div.style.left = mainDiv.offsetLeft+Math.round(parseFloat((propType=="client")?borderLeftWidth:0))+"px";
div.style.top = mainDiv.offsetTop+Math.round(parseFloat((propType=="client")?borderTopWidth:0))+"px";
div.style.height = mainDiv[propTypeHeight]+"px";
div.style.lineHeight = mainDiv[propTypeHeight]+"px";
div.style.width = mainDiv[propTypeWidth]+"px";
div.style.textAlign = "center";
div.innerHTML = propTypeWidth + " X " + propTypeHeight + "( " +
mainDiv[propTypeWidth] + " x "+ mainDiv[propTypeHeight] + " )";
div.style.background = "rgba(0,0,246,0.5)";
document.body.appendChild(div);
}
document.getElementById("offset").onclick = function(){whatis('offset');}
document.getElementById("client").onclick = function(){whatis('client');}
document.getElementById("scroll").onclick = function(){whatis('scroll');}
#MainDIV{
border:5px solid red;
}
<button id="offset">offsetHeight & offsetWidth</button>
<button id="client">clientHeight & clientWidth</button>
<button id="scroll">scrollHeight & scrollWidth</button>
<div id="MainDIV" style="margin:auto; height:200px; width:400px; overflow:auto;">
<div style="height:400px; width:500px; overflow:hidden;"></div>
</div>
Fiddle copied from: http://jsfiddle.net/shibualexis/yVhgM/3/
Using above mentioned functions to know that we reached bottom of page can be done like this:
if((window.innerHeight + window.pageYOffset) >= document.body.scrollHeight )){
//We reached bottom of page and there is no more vertical scroll can happen.
}
Hence, this is how you can make vertical scroll:
while(!(window.innerHeight + window.pageYOffset) >= document.body.scrollHeight )){
window.scrollTo(0, document.body.scrollHeight);
}
Here the condition (window.innerHeight + window.pageYOffset) >= document.body.scrollHeight ) is browser independent and can be run on Chrome, FF, IE and Safari.

How to move a "div" to certain coordinates using Javascript?

I would like to know , how to position a div block dynamically to the place where mouse clicks.
I know how to get the value of coordinates of click dynamically.
I want to know how we can move the div block to that coordinate.
I tried the following codes in SO, but nothing is working
document.getElementById('someID').style.position='absolute';
document.getElementById('someID').style.left='500px';
document.getElementById('someID').style.top='90px';
and the below code
var d = document.getElementById('yourDivId');
d.style.position = "absolute";
d.style.left = x_pos;
d.style.top = y_pos;
Can anyone tell me how to do it.
Thanks,
You have missed the units in your position assigning sentence.
To get the mouse position (on click):
(function() {
window.onmousedown = handleMouseMove;
function handleMouseMove(event) {
event = event || window.event; // IE-ism
console.log(event.clientX);
moveDiv(event.clientX,event.clientY);
}
})();
Then send the position to a function to change the position of your div, adding the pixels unit, don't forget it!
function moveDiv(x_pos,y_pos){
var d = document.getElementById('myDiv');
d.style.left = x_pos + "px";
d.style.top = y_pos + "px";
}
Full Code:
(function() {
window.onmousedown = handleMouseMove;
function handleMouseMove(event) {
event = event || window.event; // IE-ism
console.log(event.clientX);
moveDiv(event.clientX,event.clientY);
}
})();
function moveDiv(x_pos,y_pos){
var d = document.getElementById('myDiv');
d.style.left = x_pos + "px";
d.style.top = y_pos + "px";
}
DEMO
try
document.body.addEventListener('click', function(e) {console.log(e)})
you got a mouseevent object where its properties clientX, clientY gives the location of mouse click.
You can then use this to re-position your div.
You need to add px after d.style.left and d.style.top.
Try this:
<style>
#someID {
position:absolute;
left: 0px;
top: 0px;
height: 50px;
width: 50px;
background: red;
}
</style>
<div id="someID">
</div>
<script>
var ele = document.getElementById('someID');
document.onclick = function(e) {
ele.style.top = e.offsetY + "px";
ele.style.left = e.offsetX + "px";
}
</script>
Here is an example: http://jsfiddle.net/s99d4/
JS
var a = document.getElementById('a');
document.onclick = function(e){
a.style.top = e.clientY + 'px';
a.style.left = e.clientX + 'px'
}
CSS
div {
position: absolute;
}
JSFiddle
You can use this simple line of Jquery instead of going those complicated routes.
$("#divId").hide();
$('body').click(function(event) {
$("#divId").show().css( {position:"absolute", top:event.pageY, left: event.pageX});
});
First you hide the div you want to move (OR don't hide it)
Then move it wherever the user clicks. See FIDDLE
EDIT: Never mind, not all of them look so complicated anymore... Goodluck. :)
Hope this helps.
Mike
Use
d.style.position = "absolute";
d.style.top = "980px"; //or whatever
d.style.left = "970px"; //or whatever
Remember that d.style.top is the y-axis and d.style.left is the x-axis.
Therefore,
d.style.top = e.clientY + "px";
d.style.left = e.clientX + "px";
Here is a full function for this code:
document.onmousemove = getCoords;
function getCoords(e) {
e = e || window.event;
var x = e.clientX;
var y = e.clientY;
var div = document.getElementById("MYDIV");
div.style.position = "absolute";
div.style.top = y + "px";
div.style.left = x + "px";
}

finding the DOM scrollbar width

I would like to find the pixel width of the vertical and horizontal scrollbars.
I know that they are different for different OSes/browsers.
I found this code that attempts to detect it, but alas, it doesnt seem to work on IE7:
function scrollbarWidth() {
var scrollbarWidth = 0;
if ($.browser.msie) {
var $textarea1 = $('<textarea cols="10" rows="2"></textarea>')
.css({ position: 'absolute', top: -1000, left: -1000 }).appendTo('body'),
$textarea2 = $('<textarea cols="10" rows="2" style="overflow: hidden;"></textarea>')
.css({ position: 'absolute', top: -1000, left: -1000 }).appendTo('body');
scrollbarWidth = $textarea1.width() - $textarea2.width() + 2; // + 2 for border offset
$textarea1.add($textarea2).remove();
} else {
var $div = $('<div />')
.css({ width: 100, height: 100, overflow: 'auto', position: 'absolute', top: -1000, left: -1000 })
.prependTo('body').append('<div />').find('div')
.css({ width: '100%', height: 200 });
scrollbarWidth = 100 - $div.width();
$div.parent().remove();
}
return scrollbarWidth;
}
This function should give you the width of the vertical scrollbar:
function scrollbarWidth()
{
var outer = document.createElement("div");
outer.style.visibility = "hidden";
outer.style.width = "100px";
// for win 8
outer.style.msOverflowStyle = "scrollbar";
document.body.appendChild(outer);
var widthNoScroll = outer.offsetWidth;
// force scrollbars
outer.style.overflow = "scroll";
// add innerdiv
var inner = document.createElement("div");
inner.style.width = "100%";
outer.appendChild(inner);
var widthWithScroll = inner.offsetWidth;
// remove divs
outer.parentNode.removeChild(outer);
return widthNoScroll - widthWithScroll;
}
The main steps of this function are the following:
Create an outer div of width 100px
Then forces the scrollbar to appear in the outer div
Create a new inner div and append inside the outer div. Set its height to 100%
Calculate the difference between both widths.
Similarly, you can also get both the width of the vertical scrollbar, and the height of the horizontal scrollbar, setting a given height to the outer div, and calculating also the height difference of both divs, like this:
function scrollbarWidthHeight()
{
var outer = document.createElement("div");
outer.style.visibility = "hidden";
outer.style.width = "100px";
outer.style.height = "100px";
// for win 8
outer.style.msOverflowStyle = "scrollbar";
document.body.appendChild(outer);
var widthNoScroll = outer.offsetWidth;
var heightNoScroll = outer.offsetHeight;
// force scrollbars
outer.style.overflow = "scroll";
// add innerdiv
var inner = document.createElement("div");
inner.style.width = "100%";
inner.style.height = "100%";
outer.appendChild(inner);
var widthWithScroll = inner.offsetWidth;
var heightWithScroll = inner.offsetHeight;
// remove divs
outer.parentNode.removeChild(outer);
return {
width: widthNoScroll - widthWithScroll,
height: heightNoScroll - heightWithScroll
};
}
Tested in chrome, firefox, IE6, IE8, and safari.
It also uses native JavaScript (DOM functions), and doesn't use external dependencies like jQuery :)
Why are you trying to do this? Some context would be nice. If you're trying to make custom theme-able scrollbars, there are many scripts to do this, a good one being jQuery Scrollbars.

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 ;

Sliding Div to auto height

I have a div that I slide in and out.
To do this I just increase the height by 2px every second until a preset height from a height of 0.
Is there anyway to determine the content height of the div as the content is unpredictible height considering the starting properties of the div are display:none and height:0?
Thank you.
The trick is to temporarily show it, measure the height, then hide it again. And if you use visibility: hidden and position: absolute, it won't change the page layout while you do it.
function getElementHeight(el)
{
var styles = {
visibility: el.style.visibility,
height: el.style.height,
position: el.style.position,
display: el.style.display
};
el.style.visibility = "hidden";
el.style.height = "auto";
el.style.position = "absolute";
el.style.display = "block";
var height = el.offsetHeight;
el.style.display = styles.display;
el.style.position = styles.position;
el.style.height = styles.height;
el.style.visibility = styles.visibility;
return height;
}
If you want to get what the style height should be, you can add these two lines after var height = el.offsetHeight;:
el.style.height = height + "px";
height += (height - el.offsetHeight);

Categories

Resources