Finding div left position relative to window - javascript

I want to find the div left position relative to window.
I am doing like this
var diff = ($('.content-wrapper').outerWidth(true) - $('.content-wrapper').outerWidth()) ;
This is working fine but I want to see if there are any better ways to do it?
Any suggestion or help would be appreciated.
Thanks in advance

Use getBoundingClientRect.
var left = document.querySelector('div').getBoundingClientRect().left;

You can use getBoundingClientRect.
function getOffsetLeft() {
var testDiv = document.getElementById("test");
document.getElementById("demo").innerHTML = testDiv.getBoundingClientRect().left;
}
html, body {
margin: 0;
}
#test {
left: 100px;
margin: 10px;
padding: 10px;
width: 300px;
position: relative;
border: 5px solid black
}
<div id="test">
<p>Click the button to get getBoundingClientRect().leftt for the test div.</p>
<p><button onclick="getOffsetLeft()">Try it</button></p>
<p>offsetLeft is: <span id="demo"></span></p>
</div>

Use the offset() method
var diff = $('.content-wrapper').offset().left - $(window).scrollLeft();

only this code is enough
$('.content-wrapper').offset().left
I have tested using following code
html, body {
margin: 0;
}
.content-wrapper{
position: relative;
left: 100px;
width: 200px;
height: 200px;
border: 1px solid black;
}
<div style="position:relative; left: 40px; width: 500px;height:auto; border: 1px solid black;">dfgdfgdf
<div class="content-wrapper">
dfs sf dsfds fsdfdsf
</div>
</div>
I am getting left including border of parent.
result is : 141 [ self div left is 100 + parrent div border 1 + parrent div left 40 ]

Related

How to vertically and horizontally center a div using javascript and css margin?

I am currently trying to center a rectangle in an image with only using javascript (no css center properties). However, even if the numbers are right, the showing is wrong.
To do this, I use the following code :
$(document).ready(function() {
$(".img-zoom-container").css("width", $("#myimage").width());
$(".img-zoom-container").css("height", $("#myimage").height());
$("#lens_container").css("width", ($("#myimage").width() - $("#lens").width()));
$("#lens_container").css("height", ($("#myimage").height() - $("#lens").height()));
$("#lens_container").css("top", ($("#lens").height() / 2));
$("#lens_container").css("left", ($("#lens").width() / 2));
});
.img-zoom-container
{
border: 1px solid red;
}
#lens
{
border: 1px solid white;
width: 50px;
height: 50px;
position: absolute;
}
#lens_container
{
border: 1px solid cyan;
position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="img-zoom-container">
<div id="lens"></div>
<div id="lens_container"></div>
<img id="myimage" src="https://via.placeholder.com/600x160.png?text=Testing Image" alt="">
</div>
The item I am trying to center is the #lens_container div (appears blue on screen). I also have a white square (#lens div) of size 50px by 50px. I would like to center and to size the blue rectangle in order to have half of the square width at each side of the blue rectangle and same with height. However, as you can see when trying the code, it is not the case although the maths are correct.
I do not know if you can understand my needs, but I would really appreciate help there.
Thanks in advance.
There are 2 issues:
First, position: absolute means to position the item "to its closest positioned ancestor, if any; otherwise, it is placed relative to the initial containing block" (reference). The parent element ".img-zoom-container" is not positioned. The initial container block would be <body>, which has some padding by default.
So your #lens_container is positioned relative to <body> of the iframe, which is probably not what you expected. Moreover, <body> by default has a non-zero padding size. You may see it clearer if you simply use CSS to position everything to top: 0 and left: 0:
body {
background-color: rgba(0, 0, 0, 0.1);
}
.img-zoom-container
{
border: 1px solid red;
width: 600px;
height: 160px;
}
#lens
{
border: 1px solid white;
width: 50px;
height: 50px;
position: absolute;
top: 0;
left: 0;
}
#lens_container
{
border: 1px solid cyan;
width: 550px;
height: 110px;
position: absolute;
top: 0;
left: 0;
}
<div class="img-zoom-container">
<div id="lens"></div>
<div id="lens_container"></div>
<img id="myimage" src="https://via.placeholder.com/600x160.png?text=Testing Image" alt="">
</div>
To have both #lens and #lens_container positioned relative to .img-zoom-container, you have to give .img-zoom-container a "position" value so it can be the "position ancestor":
$(document).ready(function() {
$(".img-zoom-container").css("width", $("#myimage").width());
$(".img-zoom-container").css("height", $("#myimage").height());
$("#lens_container").css("width", ($("#myimage").width() - $("#lens").width()));
$("#lens_container").css("height", ($("#myimage").height() - $("#lens").height()));
$("#lens_container").css("top", ($("#lens").height() / 2));
$("#lens_container").css("left", ($("#lens").width() / 2));
});
.img-zoom-container
{
border: 1px solid red;
position: relative; /** this line **/
}
#lens
{
border: 1px solid white;
width: 50px;
height: 50px;
position: absolute;
}
#lens_container
{
border: 1px solid cyan;
position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="img-zoom-container">
<div id="lens"></div>
<div id="lens_container"></div>
<img id="myimage" src="https://via.placeholder.com/600x160.png?text=Testing Image" alt="">
</div>
It's still 1-2 pixels off. That is because you didn't take the border width into consideration (your second issue). You'd get a better result once you clear your head and think how you want the border widths to behave.
Depending on its container, you could just set an ID on your div like:
CONTENT .
Then in javascript, if there is an event to center it, you could make a function like:
function centerDivItem() {
document.getElementById("id1").style.alignContent = "center"
}
And then, as I said, call it from another place.

JS divs with equal coordinates have different offset

I am trying to display divs with some information after a client clicks on a small dot-like div (7x7px black background) pointing to a place on a map. It works but the distance between the dot-like div and the information div is different in every dot-information couple.
Here is the HTML/JS script. Please, don't mind that all the JavaScript and CSS are in the same file, it is done for the sake of simplicity and will be changed lately.
<html>
<head>
<meta charset="utf8" />
</head>
<body>
<div id="pointer_div"
onclick="getClickPosition(event)"
style="position:absolute; top:1px; left:1px; border: 1px solid black;
background-repeat: no-repeat; width: 1146px; height: 714px;" >
<div id="sofia"
onclick="showForecast('Sofia_381_178')"
style="position:relative; top: 381px; left: 178px;
background:black; width: 7px; height: 7px;" ></div>
<div id="plovdiv"
onclick="showForecast('Plovdiv_512_435')"
style="position:relative; top: 512px; left: 435px;
background:black; width: 7px; height: 7px;" ></div>
<div id="ruse"
onclick="showForecast('Ruse_77_662')"
style="position:relative; top: 77px; left: 662px;
background:black; width: 7px; height: 7px;" ></div>
<div id="result_data"
style="visibility:hidden; width:300px; height:100px;
border: 1px solid black; background:white;"/></div>
</div>
<script language="JavaScript">
function showForecast (strr) {
var splits = strr.split('_');
var xcoord = splits[2];
var ycoord = splits[1];
if (xcoord>810) xcoord= xcoord-300;
if (ycoord>610) ycoord= ycoord-100;
var resultDiv= document.getElementById("result_data");
resultDiv.style.visibility="visible";
resultDiv.style.position = "relative";
resultDiv.style.left = xcoord;
resultDiv.style.top = ycoord;
resultDiv.innerHTML = 'Forecast for: ' + splits[0];
};
</script>
</body>
</html>
So, when I click on div "plovdiv", info div appears some 30px below the dot-div, but when I click "ruse" the info div shows right below the dot. I checked both in Firefox and SeaMonkey browsers and they behave identically.
I tried to put the script in jsfiddle but it was showing all the info divs at the top left of the page and I couldn't fix that. Here it is anyway, if anyone is interested jsfiddle.
The coordinates for the info divs are passed to the JS function in a string, and they are the same as those of the dot divs (one of the reasons I kept the css in the html file). I hope someone with better understanding of JS will be able to explain that.
It's because you are using position:relative on your divs, which moves them from the position they would be in by default. So (because divs are a block element) ruse would be under plovdiv which would be under sofia, then they are moved by the top and left values. Make them all position: absolute and they'll behave uniformly.
Here's your code working in jsfiddle(I added px units to your js): https://jsfiddle.net/wkz6dj04/5/
#sofia {
position: absolute;
top: 381px;
left: 178px;
background: black;
width: 7px;
height: 7px;
}
#plovdiv {
position: absolute;
top: 512px;
left: 435px;
background: black;
width: 7px;
height: 7px;
}
#ruse {
position: absolute;
top: 77px;
left: 662px;
background: black;
width: 7px;
height: 7px;
}
Here's the code working with the above modifications: https://jsfiddle.net/wkz6dj04/6/
If you want the gap back in, I suggest using margin-top on your #result_data like in this fiddle: https://jsfiddle.net/wkz6dj04/7/

How to attach scroll bar into a div section?

I've just wrote a page with couple div-s and little CSS and javascript.
I don't know how to insert scroll bar into one of my div.
Code is not that hard to understand. CSS and javascript are included in code.
<html>
<head>
<style>
#container
{
vertical-align: top;
width: 98%;
height: 90%;
padding: 5px;
}
#discussion {
width: 99%;
height: 90%;
overflow-y: scroll;
border: 1px solid #ccc;
padding: 5px;
text-align: left;
/*position: absolute; bottom: 0; left: 0;*/
position: relative;
}
#content
{
overflow-y: auto;
position: absolute; bottom: 0; left: 0;
}
#message {
width: 100%;
vertical-align:bottom;
padding: 5px;
border: 1px solid #ccc;
}
</style>
<script>
function init(){
var message = $('#message');
var content = $('#content');
message.keypress(function (e) {
if (e.keyCode == 13 && message.val().length > 0) {
content.append(message.val() + "<br/>");
//content.scrollTop(discussion.get(0).scrollHeight); //works fine with top to down
message.val('').focus();
}
});
};
</script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body onload="javascript:init();">
<div id="container">
<div id="discussion">
<div id="content"></div>
</div>
<input id="message" type="text" placeholder="Hit Enter button to insert"/>
</div>
</body>
</html>
I need scroll bar when content gets out of discussion section.
Thing is when I insert some text with from top to bottom flow scroll bar works fine.
Unfortunately, all text has to be inserted from bottom to top flow.
---------------
-
-
-
-
- first text
---------------
---------------
-
-
-
- first text
- second text
---------------
---------------
- second text
- third text
- fourth text
- fifth text
- sixth text
--------------- now I need a scroll bar to see first text.
You set the height to 90%, but it doesn't know what it's 90% of.
If you want it set to 90% of the body, you'll need to set html,body {height: 100%;}.
Then you need to remove the absolute positioning you put on the content.
Working fiddle here: http://jsfiddle.net/davidpauljunior/2PpqN/
The main cause for the problem is you missed to set the width and height for #content div.
So add it
width: 100%;
height: 100%;
Also for the parent element discussion, instead of using % value stick to static values for height so that user can view it. Currently it is very small to view the scroll.
width: 100%;
height: 200px;
JSFiddle
Hope you understand.
You need to remove overflow from #discussion and change postion to relative in #content
CSS
#discussion {
width: 99%;
height: 90%;
border: 1px solid #ccc;
padding: 5px;
text-align: left;
/*position: absolute; bottom: 0; left: 0;*/
position: relative;
}
#content
{
overflow: auto;
position: relative;
height:100px;
width:100%;
}
updated fiddle

Put overlay on document with transparent window

I would like to do something with my document which is quite unique (haven't seen it before) and thus maybe not even possible.
What I would like is to have a div which will overlay everything in the document, maybe give it background black so that nothing is visible. Second I would like to have a small squire window in the overlay which doesn't share the black background, in fact it is somewhat transparent and therefore it would be possible to 'peek' trough that window to see document content. But only the content where this window is. It would be kinda like those "zoom" plugins in which only a small portion is being zoomed, but in this case it would show specific content. Any idea how to create such a thing?
An example of what you can do is the following (it may not be the best but it works)
HTML
<div id='peakview'></div> <!-- This div is your view window -->
<div id='out'>
<div class='overlay'></div>
<div class='overlay'></div>
<div class='overlay'></div>
<div class='overlay'></div>
</div>
The <div> inside of #out will re-size accordingly to the position of #peakview creating the illusion of a full overlay. This can be done with simple css and some calculus.
Mainly what you need is the position of the element on screen.
var h = $(this).offset().top;
var l = $(this).offset().left;
var r = ($(window).width() - ($(this).offset().left + $(this).outerWidth()));
//right offset
var b = ($(window).height() - ($(this).offset().top + $(this).outerWidth()));
//bottom offset
In my example I used .draggable() from jQuery UI to move the div around. And while dragging the 4 divs shown above are adjusting their height and width to fill up the space between #peakview and document border.
An example for the first div
$('.overlay:eq(0)').css({
top: 0,
left: 0,
width: '100%',
height: h //the height is always changing depending on the #peakview .offset().top
});
In this fiddle you will see how the filling divs behave
Another ruff start:
http://jsfiddle.net/XDrSA/
This require some extra work, but it may suit your needs.
HTML:
<div id="yourContent" style="width: 300px; margin:100px auto;">
<input type="button" id="zoom" value="Click to zoom"/>
</div>
<div id="zoomer">
<div id="window">This is your "window"</div>
<div id="overlay_top"></div>
<div id="overlay_left"></div>
<div id="overlay_right"></div>
<div id="overlay_bottom"></div>
</div>
CSS:
body {
margin:0;
padding:0;
}
#zoomer {
height: 100%;
width: 100%;
position: absolute;
top: 0;
display: none;
}
#overlay_top {
height: 20%;
width: 100%;
background-color: black;
position: absolute;
top: 0
}
#overlay_right {
height: 100%;
width: 20%;
background-color: black;
position: absolute;
right: 0;
}
#overlay_left {
height: 100%;
width: 20%;
background-color: black;
position: absolute;
left: 0;
}
#overlay_bottom {
height: 20%;
width: 100%;
background-color: black;
position: absolute;
bottom: 0;
}
#window {
margin: 0 auto;
height: 100%;
width: 80%;
position: absolute;
background-color: rgba(0,0,0,.5);
}
And a piece of javascript:
$('#zoom').click(function() {
$('#zoomer').fadeIn();
});
You may need to stumble with the positioning, and the window will be a fixed size one. Not draggable though.

Add css border-right in a div

How can i add css border-right after a specific position using javascript. As for example take this :
<div id="test"></div>
<style>
#test {
background-color : red;
height : 30px;
width : 200px;
}
</style>
We can add css style using javascript but if i want to add css border-right after 100px in #test then how can i do that. As in the example http://jsfiddle.net/zUxmd/1/ i have added css border using javascript but if i want to add it after a specific px value how can i do it. Any help would be great.
Update :
I have the following div structure
<div id=test>
<div id="1"></div>
<div id="2"></div>
<div>
The width for #1 and #2 is calculated in javascript and the sum of the width is set to #test. Suppose now if the total width is 188px i want to visually distinguish where is 100px just like the demo http://jsfiddle.net/zUxmd/2/ prepared by tom. Is this possible in any way just like adding marker to that position. But i dont want to add any extra dummy div.
EDIT :
The demo http://jsfiddle.net/davidThomas/zUxmd/7/ put up by david is exactly what i want. Any better idea would be appreciated.
Okay, a border for an element appears on the border of that element. The border represents the outer-most boundary of that element, so it cannot appear within the element itself, nor can it be a different length than the element side upon which it appears.
However, that said, you can sort of emulate what you want, clumsily, through addClass() and the ::after pseudo-element:
CSS:
#test.amended {
width: 100px;
position: relative;
border-right: 2px solid blue;
}
​#test.amended::after {
content: '';
position: absolute;
top: 0;
left: 102px;
bottom: 0;
display: inline-block;
width: 98px;
background-color: red;
}​
jQuery:
$(document).ready(function(){
$('div').addClass('amended');
});
JS Fiddle demo.
Edited to add a...messy (non-optimised) purely-demonstrative (and unrecommended) JavaScript solution:
function borderAt(el, pos) {
if (!el || !pos) {
return false;
}
else {
var pos = parseInt(pos, 10), // ensures a valid number (though there should be a sanity-check too)
w = el.clientWidth,
h = el.clientHeight,
nEl = document.createElement('div'),
pEl = document.createElement('div');
// adds a new 'parent' element to contain the elements
el.parentNode.appendChild(pEl);
// assigns the width of the specified 'el' element
pEl.style.width = w + 'px';
// appends the 'el' element to its new parent
pEl.appendChild(el);
nEl.style.backgroundColor = 'red';
// so the new sibling appears side-by-side
nEl.style.display = 'inline-block';
/* calculates the width required by the new-sibling element
in order to maintain visual continuity with the previous width */
nEl.style.width = w - (pos + 2) + 'px';
nEl.style.height = h + 'px';
el.style.borderRight = '2px solid blue';
el.style.width = pos + 'px';
el.style.display = 'inline-block'; // so the 'el' element appears side-by-side with its new sibling
// inserts new sibling after the 'el' element within its parent.
el.parentNode.insertBefore(nEl, el.nextSibling);
}
}
var el = document.getElementById('test');
borderAt(el, '160px');​
JS Fiddle proof-of-concept.
References:
document.createElement().
element.clientHeight.
element.clientWidth.
node.appendChild().
node.insertBefore().
node.nextSibling.
parseInt().
You can simulate this with CSS gradients and color stops.
Demo: http://dabblet.com/gist/2819172
Keep in mind that an alternative for IE will be needed - see CSS gradients support
If I understood correctly, I would add an inner div: http://jsfiddle.net/zUxmd/1/
Html:
<div id="test">
<div class="inner">
</div>
</div>​​​​​​​​​
Css:
#test{
background-color:red;
height: 30px;
width: 200px;
}
#test .inner {
height: 100%;
width: 100px;
}
Js:
$(document).ready(function(){
$('#test .inner').css('border-right','2px solid blue');
});
UPDATE
Here is another possibility using background image, the idea is to use a 1px x 1px blue dot, but I couldn't find that image :P
http://jsfiddle.net/zUxmd/5/
Html:
<div id="test"></div>​
Css:
#test{
background-color:red;
height: 30px;
width: 200px;
}
#test.limit {
background-image: url("http://www.scratchingpostgazette.com/forum/styles/Blue-Crush/theme/images/blue.gif");
background-repeat: repeat-y;
background-position: 100px 0;
}
​
Js:
$(document).ready(function(){
$('#test').addClass('limit');
});
​
What you're expecting is NOT POSSIBLE. You can do following trick
HTML:
<div class="wrapper">
<div id="test"></div>
</div>
CSS:
#test{
background-color:red;
height: 30px;
width: 200px;
}
.wrapper.bordered {
width: 300px;
border-right: 2px solid blue;
}
jQuery:
$(document).ready(function(){
$('div.wrapper').addClass('bordered');
});
DEMO 1
To get result what David do you can try:
HTML:
<div id="test">
<span class="bordered"> </span>
</div>
CSS
#test{
background-color:red;
height: 30px;
width: 200px;
position: relative;
}
.bordered {
width: 2px;
background: blue;
height: 30px;
position: absolute;
}
jQuery:
$(document).ready(function(){
$('span.bordered').css('left', '100px');
});
DEMO 2
You can't.
A border can only appear along the (whole) edge of an element.
Something like this would give the effect you're looking for, but it involves adding an additional element.
http://jsfiddle.net/zUxmd/2/
if you want to have multiple borders try :after and :before;
#test {
background: red;
border: 1px solid #bbbbbb;
width: 200px;
height: 200px;
margin: 50px auto;
position: relative;
}
#test:before {
border: 1px solid blue;
content: '';
width: 198px;
height: 198px;
position: absolute;
}
#test:after {
content: '';
position: absolute;
width: 196px;
height: 196px;
border: 1px solid yellow;
left: 1px; top: 1px;
}
http://jsfiddle.net/hHxHN/3/

Categories