javascript - center div (position:absolute) vertically and horizontally to screen view - javascript

I am trying to make a usercript that overlays text boxes over images: It uses a draggable menu using interactjs with fixed position. The menu has a button and I need it to create a div of 20px*60px and show it at the center of the screen view (so not to scroll to the bottom of the page and drag it from there). I can do it (somewhat) by using:
var div = document.getElementById("inserted_div_2");
div.style.position = 'fixed';
div.style.top = '50%'; //relative to screen
div.style.left = '50%';
From there I can drag/resize it to where I want over the image (also using interactjs) but then, how can I change it to position:absolute so it scrolls with the content keeping the same position over the images (eg: in the top left corner of img2)? something like:
var posX = div.getPosX(); //relative to page; in %, px or em
var posY = div.getPosY();
// when I change it from fixed to absolute the div goes back to the bottom of the page
div.style.position = 'absolute';
div.style.left = posX;
div.style.top = posY;
The HTML structure looks something like this:
<body>
...
<div id="content">
...
<img src="/img1.jpg"> // size and number of imgs is variable.
<img src="/img2.jpg"> // are in a strip format.
<img src="/img3.jpg">
...
</div>
...
<div id="overlays">
//eg: div1 was dragged from the center of screen
//into in between img1 and img2
<div id="inserted_div_1">Text</div>
//now I need to do the same for div2,
//dragging it to the top left corner of img2
<div id="inserted_div_2">Text</div>
</div>
</body>
I would prefer not using jQuery or another library, but if it is too difficult then I will use it.
Thanks!

You can use offsetTop and offsetLeft to get the element's position (in px) relative to the page.
var posX = div.offsetLeft;
var posY = div.offsetTop;
div.style.position = 'absolute';
div.style.left = posX;
div.style.top = posY;
UPDATE
The values returned by offsetTop and offsetLeft do not include the transform:translate styles applied. I created a test case - its not dragable but it shows you how to calculate the relative positions by adding the offset and the translate values:
var div = document.getElementById("inserted_div_2");
var content = document.getElementById("content");
function testpos(){
var ol = div.offsetLeft,
ot = div.offsetTop,
cs = window.getComputedStyle(div, null),
tr = cs.getPropertyValue("-webkit-transform") ||
cs.getPropertyValue("-moz-transform") ||
cs.getPropertyValue("-ms-transform") ||
cs.getPropertyValue("-o-transform") ||
cs.getPropertyValue("transform") ||
false;
//outputs something like 'matrix(1, 0, 0, 1, 80, 90)'
var values = tr.replace(/[^0-9\.\,]/g,'').split(','),//split into array
tx = values[4] || 0,//take the x value (else 0)
ty = values[5] || 0;//take the y value (else 0)
//
content.innerHTML+=("<hr />position: "+div.style.position+"<br />");
content.innerHTML+=("offsetLeft:"+ol+", offsetTop:"+ot+"<br />");
content.innerHTML+=("translate-x:"+tx+", translate-y:"+ty+"<br />");
//so the actual position is the offset + the translate ==
var x = parseInt(ol) + parseInt(tx),
y = parseInt(ot) + parseInt(ty);
content.innerHTML+=("x:"+x+" y:"+y+"<br />");
}
/* TEST */
//1 set to fixed
div.style.position = 'fixed';
testpos();//test position
//2 move using transfor:translate
div.style.transform = 'translate(80px,90px)';
testpos();//test position (note the offset does not include the transform)
/3 set to absolute and get the position
div.style.position = 'absolute';
testpos();
http://jsfiddle.net/u3ay74bs/

you can use css for center div vertically and horizontally
for example
#content{
position:absolute;
width:100px;
height:100px;
left:50%;
top:50%;
margin-left:-50px; /*half width*/
margin-top:-50px; /*half height*/
}
<div id='content'>
...
</div>
if width equal 100px margin-left equal -50px
if width equal 200px margin-left equal -100px
and so on
margin-left half width
and
margin-top half height

Related

appendchild after some specific pixel inside div javascript

I want to append a div inside another div after some specific pixel. For example, First, I created a Div than I calculate its Height with offsetHeight. Now I want to append a Div Inside parent Div in middle (Half of parents div height)
var ts = document.querySelectorAll('article')[0];
var ks = ts.offsetHeight;
var lirf = ks/2;
<article>Giving some Height to it.<br/>
Giving some Height to it.<br/>
Giving some Height to it.<br/>
Giving some Height to it.<br/>
</article>
Want to Append Child at lirf px in above code
Find Answer Close Enough
When I use absolute position my div overlap other as shown in below code:
<div id='get' style=''>kad</div>
<article >Giving some Height to it.<br/>
Giving some Height to it.<br/>
Giving some Height to it.<br/>
Giving some Height to it.<br/>
</article>
<script>
var ts = document.querySelectorAll('article')[0];
var ks = ts.offsetHeight;
var lirf = ks/2;
var kk = document.getElementById('get');
kk.style.position = "absolute";
kk.style.top=lirf+'px';
</script>
var ts = document.querySelectorAll('article')[0];
var ks = ts.offsetHeight;
var lirf = ks/2;
var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "red";
div.style.position = 'absolute';
div.style.top= lirf+'px';
document.querySelectorAll('article')[0].appendChild(div);
Hope this helps!
If vertically centering an element is your aim, go through this https://vanseodesign.com/css/vertical-centering/

how can i measure cursor position in a div..?

i don't know what should be the question title..sorry for this.
but i explain that what i want to do.
i have a div with class name "scroll-inner-container" this div height is 70vh.
when my mouse hover into this div from top to 10% (this is the mouse hover area 0% to 10% in this div) and bottom to 10% then a function will start.
How can I measure this area into this div by using js...?
My html code looks like:
<div class="scroll-inner-container">
<div class="paragraph-space content">
<h1>top position</h1>
<p>Lorem ipsum dolor...</p>
<h1>end position</h1>
</div>
my css code here for this div:
.scroll-inner-container{
height: -moz-calc(70vh + 0px);
height: -webkit-calc(70vh + 0px);
height: calc(70vh + 0px);
overflow: auto;
object-fit: cover;
background-color: yellow;
position: relative;
}
I've previously used code similar to this for a project, copied from a previous question How to get mouse position - relative to element
var x,y;
$("#div1").mousemove(function(event) {
var offset = $(this).offset();
x = event.pageX- offset.left;
y = event.pageY- offset.top;
$("#div1").html("(X: "+x+", Y: "+y+")");
});
Once the mouse goes past a specified point on the Y axis, you can execute your code.
I think this code segment will help you. It will check the mouse position with your parent container, You can call your function inside the if condition.
var obj = $('.scroll-inner-container');
var top, left, bottom, right;
var excldH,objHeight,objWidth;
getPos(obj)
//Calls fuction on mouse over
obj.mousemove(function(e) {
handleMouseMove(e)
});
//Get position of mouse pointer
function handleMouseMove(e) {
var posX = e.clientX;
var posY = e.clientY;
if(posY > top+excldH && posY < bottom - excldH){
//Here your stuffs go
console.log(posX)
console.log(posY)
}
}
// Get position of the div 'scroll-inner-container'
function getPos(obj) {
var offsets = obj.offset();
objHeight = obj.height();
objWidth = obj.width();
excldH = objHeight/10; //Caculating 10% height
top = offsets.top,
// left = offsets.left,
bottom = top+objHeight,
// right = left+objWidth
}
Here is a jsfiddle for that
I tried to add here as snippet, but didn't worked. You can inspect the result on console.

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 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