How to get the offset position of a div - cross-browser issue - javascript

I have a markup like this
<div>
<div>hello</div>
<div>World</div>
</div>
I am using first div as float right and second one as float left.
The problem is to get the position of the end corner of "World" div
I used the JS like this
var left = $('.inner-page-right-content').offset().left;
left = -(900- left);
$('#inner-page-container').css('background-position',left);
The code works in Chrome and Safari but not in Firefox
where it is showing the real distance from window (without float).
Any help or insight will be really appreciated

This throws the same result in Chrome and Firefox
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<style type="text/css">
#hello {
float: right;
width: 100px;
background: grey;
color: white;
text-align:center;
}
#world {
float: left;
width: 100px;
background: grey;
color: white;
text-align:center;
}
#result {
clear: both;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
var oWorld = $("#world").get(0);
var rect = oWorld.getBoundingClientRect();
$("#result").html("top: "+rect.top+", Right: "+rect.right);
});
</script>
</head>
<body>
<div>
<div id="hello">hello</div>
<div id="world">World</div>
</div>
<div id="result"></div>
</body>
</html>

You could try getBoundingClientRect()
// Assuming your 'world' div has an id="world"
var rect = document.getElementBydId('world').getBoundingClientRect();
rect.left // x position of #world relative to viewport
rect.top // y position of #world relative to viewport
rect.width // width of #world, including padding and borders
rect.height // height of #world, including padding and borders
rect.offsetWidth // width of #world - IE8 and below
rect.offsetHeight // height of #world - IE8 and below
Important notes
left and top positions are relative to viewport, meaning that
scrolling is NOT taken into account. Add scroll x and y values to get
real absolute position.
CSS transforms are taken into account.
See the doc on MDN

Try
dom.getBoundingClientRect()
You can use this method get a dom's rectangle. It containes left top bottom right position
relative to the browser.

Related

Horizontally and vertically centered iframe with aspect ratio 16:9 that uses as much screen estate as possible without being cropped anywhere

Requirements:
The HTML: The iframe HAS to be inside of a containing div. See code down below.
The CSS: The container should be able to have ANY valid width and height using the vw and vh viewport units. Se code down below.
Yes, the width and height HAS to be in vw and vh.
The static video preview image should NEVER be cropped.
The static video preview image should NOT have any black bars above and below (letterboxing).
The static video preview image should NOT have any black bars to the left or to the right (pillarboxing).
The static video preview image should use as much space estate as possible inside the div that contains it.
The static video preview image should ALWAYS keep its aspect ratio of 16:9.
Scrollbars should NEVER appear.
The static video preview image should be centered vertically as well as horizontally inside the div that contains it.
Responsive Web Design.
When resizing the browser or viewport all of the above requirements should be fulfilled.
HTML:
<div class="container">
<iframe></iframe>
</div>
CSS:
.container {
width:90vw;
height:50vh;
}
Same solution, but no extra markup for keeping the ratio.
JsFiddle with same comments totally not needed.
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8">
<title>Fully Container Centred Iframe</title>
<meta name="generator" content="PSPad editor, www.pspad.com">
<style>
.container {
display:table-cell; /* (specs: omitted table parts, the browser will insert mandatory elements in the dom tree) */
position:relative;
padding:; /* optional, margins ignored */
width:100vw; /* any value */
height:1vh; /* will expand by the :before element */
overflow:hidden; /* hide eventual black bars */
background:tan; /* bg-colors just for demo testing */
vertical-align:middle;
text-align:center;
}
.container:before {
display:block;
padding-top:56%; /* keeps the 16/9 ratio for the AP */
height:0;
background:red;
content:"\a0";
}
.container iframe {
position:absolute; /* to be ratio consistent */
top:-.5%;
left:-.5%; /* overflow eventual black bars */
border:0;
width:101%; /* grow some to avoid thinner black bars */
height:101%;
overflow:hidden; /* for html5 browsers the html attribute is depreciated */
background:gold;
}
</style>
</head><body>
<div class="container">
<iframe scrolling="no" src=""></iframe>
</div>
</body></html>
Using JavaScript, you can listen for the resize event, which fires whenever the browser's window changes shape. Then, with some simple algebra you can calculate the dimensions of the iframe based on the dimensions of the container. Here is a demo that shows all of the requirements.
"use strict";
var container = document.querySelector('.container');
var frame = container.querySelector('iframe');
function resizeVideo() {
frame.width = frame.height = 0;
var width = container.offsetWidth;
var height = container.offsetHeight;
if (height * (16 / 9) <= width) {
frame.height = height;
frame.width = height * (16 / 9);
} else {
frame.width = width;
frame.height = width * (9 / 16);
}
}
window.addEventListener('load', resizeVideo);
window.addEventListener('resize', resizeVideo);
.container {
width: 90vw;
height: 50vh;
display: table-cell;
text-align: center;
vertical-align: middle;
}
<div class="container">
<iframe src="https://www.youtube.com/embed/BKhZvubRYy8" frameborder="0" allowfullscreen></iframe>
</div>
if you want Responsive use
.container, iframe {
width:100%;
height:auto;
}
.container {
width:90vw;
height:50vh;
}
.container iframe {
width: 100%;
height: 100%;
}
Seems to work quite nicely in this fiddle https://jsfiddle.net/1q10L7hj/
why don't you just use the calc method to get the aspect ratio width you are wanting?
HTML
<div class="container">
<iframe src="" frameborder="0"></iframe>
</div>
SCSS
<style>
$width = 80vw;
.container {
width: $width;
height: calc(($width/16) * 9);
position: relative;
}
iframe {
position: absolute;
width: 100%;
height: 100%;
top: 50%;
left: 50%;
-webkit-transform: translate(+50%, -50%);
transform: translate(+50%, -50%);
}
</style>
then you can change the width of it anywhere and apply whatever positioning you want on the container div and the iframe with follow suit
I think the table-cell display could solve this. Just apply it on the container so the iframe is the content
According to specs the browser will insert dummy elements where it needs to render the cell correctly and fully centre and to contain its content and if it need, grow with it.
The requirements: I think some of them is beyond the scope of your question, they will also depend on what is loaded in the iframe, out of control of this container document. My suggested code is simple, but I believe it meets all requirements possible for the iframe parent and still be crossbrowser friendly.
The forbidden black bars and the mandatory aspect ratio could still be at fault in the loaded document. If you can't control whats loaded, the last option might be the "srcdoc" and "seamless" attributes, but that would exclude e.g. all IE versions.
JsFiddle with some comments totally not needed. Hope the edit below solves the case.
Anyway, I had fun! Thanks! :)
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8">
<title>Fully Container Centred Iframe</title>
<meta name="generator" content="PSPad editor, www.pspad.com">
<style>
.container {
display:table-cell;
padding:;
width:100vw;
height:20vh;
background:tan;
vertical-align:middle;
text-align:center;
}
.container .ratio{
display:inline-block;
position:relative;
padding-bottom:56%;
width:100%;
height:0;
overflow:hidden;
vertical-align:middle;
}
.container iframe {
position:absolute;
top:-1%;
left:-1%;
border:0;
width:102%;
height:102%;
overflow:hidden;
vertical-align:middle;
}
</style>
</head><body>
<div class="container">
<div class="ratio">
<iframe scrolling="no" src=""></iframe>
</div>
</div>
</body></html>
I have gotten the result you wanted, I however had to add an extra div as the parent of the .container class. This JSFiddle should work for users on chrome (Windows desktop version) however when I tried to use the same fiddle on Edge and IE11 I found that it would create the undesired letter-box effect due to the image cover zooming too far out.
HTML
<div id="wrapper">
<div class="container">
<iframe scrolling="no" src="https://www.youtube.com/embed/YL9RetC0ook" frameborder="0" allowfullscreen>
</iframe>
</div>
</div>
CSS
body {
margin: 0;
}
#wrapper {
width: 90vw;
height: 50vh;
}
.container,iframe {
width: 100%;
height: 100%;
}
I am not sure if this works for Firefox, so perhaps if you have Firefox you can try it on my JSFiddle. However for Chrome (at the very least) this should be the solution you where looking for as stated by the requirements you listed.
I would recommend using a JavaScript window.resize listener to solve this kind of an issue. Cannot write code today cause I have a pretty tight schedule, but I'll try writing an algo:
On window resize, compute window width (wW) and window height (wH);
Determine container width (cW) as per wW (say cW = wW-10 to get almost all the width available - you can omit the -10 if you want);
Determine container height (cH) as per cW computed above: cH = cW * 9 / 16;
Now, if cH > wH (i.e. the container is not fitting into the screen vertically because it is too wide), we should revise cW as per available window height. In this case, cH = wH-10 (to get almost all the vertical space available - again, you can omit the -10 if you want) and then cW = wH * 16 / 9;
You should have a valid cW and cH now to make you container fit into the window without going out of the screen and you can apply it to the container.
To center the container to the screen, use position: absolute, left: 50%; top: 50%; in your CSS. When you update the cW and cH, also update margin-left: -(cW/2); margin-top: -(cH/2);
This is the concept - you can improvise as per your needs. I hope it helps.

How to create image inside a scrollable div

I have a div, an image(arrow.gif), another image(Untitled-1.jpg), two textboxes and a button.
I want to move the arrow.gif within a scrollable div with an image inside.
But i'm having a trouble creating the div into a scrollable one (making the Untitled-1.jpg fill the div) and moving the arrow.gif based on the Untitled-1.jpg's coordinates. Can anyone help me with this? Any help/assistance will be greatly appreciated .
<!DOCTYPE html>
<html>
<head>
<title>Move to Click Position</title>
<style type="text/css">
body {
background-color: #FFF;
margin: 30px;
margin-top: 10px;
}
#contentContainer {
border: 5px black solid;
background-color: #F2F2F2;
cursor: pointer;
background-image:url('Untitled-1.jpg');
background-repeat: no-repeat;
background-size: fixed;
width:1030px;
height:912px
}
#thing {
position: relative;
left: 50px;
top: 50px;
height: 68px;
width: 41px;
transition: left .5s ease-in, top .5s ease-in;
z-index: 10000;
}
</style>
</head>
<body>
<div id="contentContainer">
<img id="thing" src="arrow.gif" >
</div>
<form method="post" action="">
<input type="button" value="submit" name="submit" onclick="getClickPosition()">
<input type="text" id="valuex" name="valuex">
<input type="text" id="valuey" name="valuey">
</form>
<script src="prefixes.min.js"></script>
<script>
function getClickPosition() {
var theThing = document.querySelector("#thing");
var container = document.querySelector("#contentContainer");
var x1 = document.getElementById('valuex').value;
var y1 = document.getElementById('valuey').value;
var parentPosition = getPosition(x1.currentTarget);
var parentPosition = getPosition(y1.currentTarget);
var xPosition = x1 - parentPosition.x - (theThing.clientWidth / 2);
var yPosition = y1- parentPosition.y - (theThing.clientHeight / 2);
theThing.style.left = xPosition + "px";
theThing.style.top = yPosition + "px";
}
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 };
}
</script>
</body>
</html>
First things I'm noticing is that you have:
background-size: fixed;
Fixed isn't an option for the background-size property.
You also have:
height:912px
Which is missing a semicolon, and will break your stylesheet further on.
1) Full-size background
If you want your 'Untitled-1.jpg' image to fill the frame you could set background-size to either cover or contain.
2) Scrollable div
In order to change your div into a scrollable one you can do so as follows:
#div{
width:1030px;
height:912px;
overflow: auto;
}
Overflow auto will add horizontal and vertical scrollbars to the div in the event that it extends outside its bounds. Or can use scroll if you want scrollbars to always be visible on the div.
You could also use overflow-x and overflow-y to specify which orientation you want scrollbars to appear.
3) Moving the thing
You're on the right track setting the position of the thing, there's a bit of fiddly stuff involved though to get it all functioning. See my Fiddle.
Demo
I've modified your code a fair bit, but in this fiddle you can change the position of the thing within the scrollable div, using the coordinate boxes.
https://jsfiddle.net/8y0qhdwx/
I'm not sure where you are heading with this, but it would be worth looking into the HTML5 canvas element, as it's built to handle the positioning of objects within it.
Hope this helps.

Child position differs from assigned if container has non-integer (%) position

I have centered (position: absolute; left: 50%; margin: -50px;) 100px width div (container).
It has absolutely positioned child div with overflow: hidden, its size is 100x2000 px (such height is for test purposes, as described below).
There is an image in child div, it is absolutely positioned.
The image is 3100x100 px, it contains frames of animation.
I am animating this image by changing its style.left from 0 to -1100px, step is 100px.
Everything is fine, but I encounter weird issue when body width is not even.
It can happen if there is scrollbar and the scrollbar has odd width (it happens for me on Chrome/Win32 for example).
In this case image visually shifts by 1 pixel horizontally as soon as animated image goes through screen edge (for 1920x1080 it happens roughly at 9-10 frame of animation).
I can't find workaround for this behavior.
Working example reproducing the problem can be found here
Child div height is set to 2000px to make sure scrollbar is visible.
If your scrollbar has even width, you can reproduce the problem by resizing your browser window to odd width.
That happens because of the browsers rounding engines. Webkit apparently has some problems with 50% on even and odd widths.
One way to overcome the issue - re-position the .outer element based on window width
document.getElementById( 'outer' ).style.left = Math.floor( window.innerWidth / 2 ) + 'px';
DEMO
You need to change .inner img position to relative and update your javascript. I made changes for you, so here is your solved code:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<style>
body {
background-color: #000000;
}
.outer {
position: absolute;
left: 50%;
margin-left: -50px;
}
.inner {
position: absolute;
width: 100px;
height: 2000px;
overflow: hidden;
}
.inner img {
position: relative;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="outer">
<div class="inner">
<img src="http://lorgame.ru/test.png" id="img">
</div>
</div>
<script language="JavaScript">
var framesCount = 30;
var framesCurrent = 0;
var framesMoveLeft = true;
var img = document.getElementById('img');
var interval = setInterval(function() {
if(framesMoveLeft == true){
framesCurrent++;
img.style.left = (img.offsetLeft - 100) + 'px';
if(framesCurrent == framesCount) framesMoveLeft = false;
} else { // Move right
framesCurrent--;
img.style.left = (img.offsetLeft + 100) + 'px';
if(framesCurrent == 0) framesMoveLeft = true;
}
}, 100);
</script>
</body>
</html>
To me this seems like a bug in Chrome. When percentages are defined in integers, they behave rather unexpectedly. Try to define the position as a decimal instead:
.outer {
position: absolute;
left: 49.99999%;
margin-left: -50px;
}
I tested this on the fiddle and it seems to do the trick.

How to place a popup message in center of the div?

I have a div block for which I am calculating its width and offset height on the basis of the calculation below. Now I am trying to place the message holder block inbetween the div block.
My aim is to show the message "popup" block in the center of the div "oID_1". Can anybody help me?
<BODY>
<head>
<script>
function msgBox(message) {
var msgbox = document.getElementById("msgbox");
msgbox.innerHTML = message;
var x = (window.innerWidth / 2) - (msgbox.offsetWidth / 2);
var y = (window.offsetHeight / 2) - (msgbox.offsetHeight / 2);
msgbox.style.top = y;
msgbox.style.left = x;
msgbox.style.display = "block";
}
</script>
<style type="text/css">
.popup {
width:100px;
height:100px;
position:absolute;
display:none;
border:1px solid green;
}
</style>
<script type="text/javascript">
function showPopup(id) {
var popup = document.getElementById(id);
var divblock=document.getElementById('oID_1');
width=parseInt(oID_1.style.width);
var x = (width / 2) - (popup.offsetWidth / 2);
var y = (divblock.offsetHeight / 2) - (popup.offsetHeight / 2);
popup.style.top = y;
popup.style.left = x;
popup.style.display = "block";
}
</script>
</head>
<DIV CLASS="body">
<center>
<div id="popup" class="popup">
This a vertically and horizontally centered popup.
</div>
<a onclick="showPopup('popup');">Show Popup</a>
<DIV ID="oID_1" STYLE=" width:300; height:300;border:1px solid red">
</DIV>
</center>
</DIV>
</BODY>
If your element is absolute positioned and you know it's width, you can always use left: 50%; margin-left: -(half width)px
Can you use jQuery?
Take a look at center-div-with-jquery
Take a look at the following website: http://bushraaadit.appspot.com/
Now the way they have centered the div is quite simple. First we'll take a look at the HTML structure:
<div id="container">
<div id="wrapper">
<div id="center"></div>
</div>
</div>
Okay so we have three nested divs. The first one (the container) is the div within which you want to center the third div (center). The second div (the wrapper) is used to help center it. Think of it as a center tag which centers horizontally and vertically.
Now for the CSS (yes it works purely on CSS and automatically re-centers itself when the container div is resized). Give the container div any width and height you want. Now for the wrapper and the center divs.
The wrapper div must have the same width and height as the center div. If the center div needs an explicit width and height (say 50% of the container) then set it on the wrapper and set the width and height of the center as 100% (which is 100% of 50% of the container). Otherwise make the wrapper float to the left (doing so will automatically shrink it to the size of the center div).
Finally to center it we first set the position of the wrapper and center to relative. Then the wrapper div is positioned 50% to the right and the bottom from where it is (50% of the container). Then the center div is positioned 50% to the left and top from where it is (50% of the wrapper which is 50% of itself).
The resulting CSS is something like:
html, body, #container {
height: 100%;
width: 100%;
}
body {
margin: 0;
}
#container {
background-color: #FFF0F5;
}
#wrapper {
height: 50%;
left: 50%;
position: relative;
top: 50%;
width: 50%;
}
#center {
background-color: #FFE4E1;
bottom: 50%;
height: 100%;
position: relative;
right: 50%;
width: 100%;
}
The end result can be seen in this fiddle: http://jsfiddle.net/a3kVj/
Hope that helps.

How to center align pop up div using Javascript

How to align a pop up division to center of monitor/screen using javascript?
I tried using screen.width and screen.height to get center. But the division gets aligned to center of scrolling page vertically
Thanks in advance for any help and suggestions
Try this:
<div id="popup" class="popup">
This a vertically and horizontally centered popup.
</div>
<a onclick="showPopup('popup');">Show Popup</a>
<style type="text/css">
.popup {
width:200px;
height:100px;
position:absolute;
top:50%;
left:50%;
margin:-50px 0 0 -100px; /* [-(height/2)px 0 0 -(width/2)px] */
display:none;
}
</style>
<script type="text/javascript">
function showPopup(id) {
var popup = document.getElementById(id);
popup.style.display = 'block';
}
</script>
CSS explained:
The div is 200x100, you position it 50% from the top and 50% from the left, but to have it centered fully, you need to substract from that 50% values the half of the width and height, the way to do this is to use negative margins, hence margin-top should be the negative value of the height/2 and margin-left should be the negative value of the width/2.
How about just doing with CSS:
<div class="div">Some Content......</div>
.div {
margin-left: auto;
margin-right: auto;
}
try:
function msgBox(message)
{
var msgbox = document.getElementById("msgbox");
msgbox.innerHTML = message;
var x = (window.innerWidth / 2) - (msgbox.offsetWidth / 2);
var y = (window.offsetHeight / 2) - (msgbox.offsetHeight / 2);
msgbox.style.top = y;
msgbox.style.left = x;
msgbox.style.display = "block";
}
Try fixed-positioning:
#box {
position: fixed;
width: 40%;
margin: 200px 30%;
}
It's only horizontally centered. Vertical will take some playing with. I have no idea how browsers act differently with the vertical alignment.
I also had this vertical centering problem on any webpage that required scrolling.
Switching to position: fixed solved it, so:
position:fixed;
top:50%;
left:50%;
margin:-50px 0 0 -100px; /* [-(height/2)px 0 0 -(width/2)px] */
This worked in firefox, google chrome, safari (pc) and IE9.
Unfortunately, I wanted it to appear in front of an pdf file - the pop up did appear in front using Firefox, Chrome but went behind in IE9 and Safari....

Categories