Positioning div off-screen to the right using jQuery - javascript

Strictly using JavaScript, I'd like to position the following div element right outside the window, to the right, so that no horizontal scrollbar is present.
How do I do this?
HTML:
<div id = "content">
<header>
<h2>Welcome!</h2>
</header>
</div>
I was thinking something like
$( "#content" ).offset({ left: 1345});
but that unfortunately results in a scrollbar, and it isn't responsive, causing the div to be located far outside the right edge of the window when in mobile view.

If you take the window.innerWidth; value and set that as the left position value it'll hang out right outside of the viewports width.
You'd need to set either your wrapper or body to overflow: hidden; to get rid of the horizontal scroll though.
var hiddenDiv = document.getElementById('content');
var docWidth = window.innerWidth;
hiddenDiv.style.position = 'relative'; // Or absolute, depending on what you want
hiddenDiv.style.display = 'inline-block';
hiddenDiv.style.left = docWidth+'px';
http://jsfiddle.net/c62sqvdk/ <-- JsFiddle for visual example.

Why not just hide it? You can easily do it with javascript with
var link = document.getElementById('content');
link.style.display = 'none';
link.style.visibility = 'hidden';
Depends on what you need it for.
Also, check this https://daneden.github.io/animate.css/

Try
document.body.style.overflow = "hidden";
var content = document.getElementById("content");
content.style.position = "absolute";
content.style.left = window.innerWidth + "px";
jquery
$(function() {
$("body").css("overflow", "hidden")
.find("#content").css({
"position" : "absolute",
"left" : window.innerWidth
});
});
jsfiddle http://jsfiddle.net/guest271314/9zhy2xax/

Related

Cannot apply style to dynamically created elements in javascript

I have the following code:
let dynel = document.createElement('div');
dynel.className = 'foo';
dynel.style.width = '5px';
dynel.style.height = '5px';
dynel.style.backgroundColor = 'blue';
document.body.appendChild(dynel);
This code works as I expect it to, after appending the dynamic element to the document, a 5 x 5 blue box appears. The problem starts when I try to access the element via its className to style it further:
var foo = document.getElementsByClassName('foo');
foo[0].style.top = '50px';
foo[0].style.left = '200px';
This code should position the box but it does nothing, what am I doing wrong? Preferably I'm looking for a pure JS solution so no JQuery.
Thanks in advance :)
Problem
The default value of the property position of a div is static. When you try to set left/right [..] on static element it has no effect on that element.
static : every element has a static position by default, so the
element will stick to the normal page flow. So if there is a
left/right/top/bottom/z-index set then there will be no effect on that
element. relative : an element's original position remains in the flow
of the document, just like the static value.
Solution
You have to set the position property in your created element to absolute, fixed or relative.
let dynel = document.createElement('div');
dynel.className = 'foo';
dynel.style.position = "absolute"
dynel.style.width = '5px';
dynel.style.height = '5px';
dynel.style.backgroundColor = 'blue';
document.body.appendChild(dynel);
var foo = document.getElementsByClassName('foo');
foo[0].style.top = '50px';
foo[0].style.left = '200px';
top, left, right, bottom works on those elements in which position property is not static. But either absolute or relative or fixed.
As per your requirement use any of the 3 values in your CSS and styles will start to apply. Something like this would work (But it depends how you want you implemention of the code)
var foo = document.getElementsByClassName('foo');
foo[0].style.position = "relative";
foo[0].style.top = '50px';
foo[0].style.left = '200px';
NOTE: position:fixed and position:absolute would get your element out of the normal code flow and you will have to adjust accordingly.
You need to ensure that foo[0] has the position: absolute; style set.
I was inspired by #Imran Rafiq Rather to give the details example for each situation:
relative
If you just want to adjust position a little bit relative to its default position, use key word "relative"
Default position is 'static' position
var foo = document.getElementsByClassName('foo');
foo[0].style.position = "relative"; // works almost the same as default or 'static', because 'relative' is relative to it's 'static' position.
foo[0].style.top = '50px';
foo[0].style.left = '200px';
https://codepen.io/hoogw/pen/QWqRdBY
absolute
we usually want to relative to its parent div, should use 'absolute'
var foo = document.getElementsByClassName('foo');
foo[0].style.position = 'absolute'; // relative to its parent div
foo[0].style.top = '50px';
foo[0].style.left = '200px';
https://codepen.io/hoogw/pen/GRMaWKB?editors=1100
fixed
If you want to relative to whole page, use 'fixed'
var foo = document.getElementsByClassName('foo');
foo[0].style.position = 'fixed'; // relative to whole page, whole html body document
foo[0].style.top = '50px';
foo[0].style.left = '200px';
https://codepen.io/hoogw/pen/yLzWMvJ
Here is link to document https://developer.mozilla.org/en-US/docs/Web/CSS/position

How to detect page scroll to the bottom of a long div?

I have a very long div (height: 500px), and I want to detect if user scrolled to the bottom of this div.
I have seen so many answers in the stackoverflow, almost all the answers mentioned scrollTop. However, in my simple example (jsfiddle), the scrollTop is always 0. After reading the MDN, I realize maybe they are talking about scrollable div? But all I want is to detect whether user scrolled to the bottom of a normal div.
Code
<html>
<body>
<!-- This is the very very long div, which may be contained in some other divs -->
<div></div>
</body>
</html>
jQuery Code
Currently, there is no scrollBottom function of jQuery. But, I have created a function that will tell whether we can see the bottom of a specific div element or not.
let aDiv = document.getElementById("aDiv");
$(document).scroll(function () {
var y = $(this).scrollTop();
var windowHeight = $(window).height();
var bottomVal = aDiv.offsetTop + aDiv.offsetHeight- windowHeight;
let s = document.getElementById("txt");
if(y>bottomVal && y< bottomVal + windowHeight){ s.innerHTML = "You can see bottom of aDiv";}
else{ s.innerHTML = "Can't see bottom of aDiv"; }
});
You can go through the following example. This might help you.
https://jsfiddle.net/q2smtvya/3/
Update: Added Vanilla JS Code. The only change will be the following JS Code
let aDiv = document.getElementById("aDiv");
window.onscroll = function(){
var y = window.scrollY;
var windowHeight = window.innerHeight;
var bottomVal = aDiv.offsetTop + aDiv.offsetHeight- windowHeight;
let s = document.getElementById("txt");
if(y>bottomVal && y< bottomVal + windowHeight){ s.innerHTML = "You can see bottom of aDiv";}
else{ s.innerHTML = "Can't see bottom of aDiv"; }
};
You can go through the following example. This might help you.
https://jsfiddle.net/nrp7x61k/1/

need 100% div without setting a fixed height on container div

Here is a link to a JSFiddle http://jsfiddle.net/9NYcn/11/ i put together with what i would like to do, but i need to do this with pure css.
function expand(){
var sect = document.getElementById("sect");
var body = document.getElementById("main");
var panes = document.getElementById("panes");
var newHeight = 40 + "px";
var newHeight2 = 120 + "px";
var topVal = 120 + "px";
sect.style.display = "block";
sect.style.height = newHeight;
body.style.height = newHeight2;
panes.style.top = topVal;
}
In the above function i had to set the "top" property of panes in order to get this to work. i need to get it so that the panes section will work like it currently does without using javascript to change the "top" property of "panes". When the user clicks the "expand" button the div with the class "body" will expand and not stick behind or overlap the "panes" div.
I know im doing a terrible job explaining i apologize for that.
Remove the absolute positioning of .panes: http://jsfiddle.net/rHTM8/
It will make it naturally flow after the middle div.

JavaScript: Get window width minus scrollbar width

Ok, I thought this would be really simple, but it's turning out not to be. I think I'm just messing something up in my HTML/CSS, but here goes.
I have a basic page like so:
HTML
<!DOCTYPE html>
<html>
<head>
<link href='test2.css' rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="test2.js"></script>
</head>
<body>
<div id="scroll"></div>
</body>
</html>
test2.css
* {
padding: 0;
margin: 0;
}
html, body {
height: 100%;
width: 100%;
}
#scroll {
height: 100%;
width: 100%;
overflow: scroll;
background-color: black;
}
test2.js
$(document).ready(function() {
// my resolution is 1440x900
alert('innerwidth should be 1425');
// all of these return 1440
alert('body innerwidth: ' + $('body').innerWidth());
alert('document width: ' + $(document).width());
alert('window width: ' + $(window).width());
alert('scroll div innerwidth: ' + $('#scroll').innerWidth());
alert('document.documentElement.clientWidth: ' + document.documentElement.clientWidth);
alert('document.documentElement.scrollWidth: ' + document.documentElement.scrollWidth);
});
So I've got one element on the page... a div that takes up the entire screen, or rather it should be taking up the entire screen minus the scrollbars. Now, I've been doing some snooping on how to grab the width and height of a page without the scrollbars, but unfortunately, none of them return the proper value... which makes me believe I'm missing the boat in my HTML or CSS.
I looked at the following:
jquery - how to get screen width without scrollbar?
how to get the browser window size without the scroll bars
So what I need is for a method to return the value of my viewable screen minus the respective scrollbar value... so for my width, my value should be 1425 because the scrollbar is 15 pixels wide. I thought that's what innerWidth's job was, but apparently I'm wrong?
Can anyone provide any insight? (I'm running Firefox 24.)
EDIT
To add some background, I've got a blank page. I will be adding elements one by one to this page, and I need to use the width of the page when calculating the sizes for these elements. Eventually, this page will grow and grow until the scrollbar appears, which is why I'm trying to force the scrollbar there from the start, but apparently, that still doesn't do anything.
EDIT2
Here's something even more interesting... if I do document.getElementById('scroll').clientWidth, I get the proper innerWidth, but if I do $('#scroll').width() or $('#scroll').innerWidth(), they both return the max resolution... sounds like a jQuery bug.
I got this somewhere and would give credit if I knew where, but this has been succesfull for me. I added the result as padding when setting the html overflow to hidden.
Problem is that the scrollbar is a feature of the browser and not the web page self. Measurement should be done dynamically. A measurement with a scrollbar and a measurement without a scrollbar will resolve into calculating the difference in width.
Found the source: http://www.fleegix.org/articles/2006/05/30/getting-the-scrollbar-width-in-pixels
scrollCompensate = function () {
var inner = document.createElement('p');
inner.style.width = "100%";
inner.style.height = "200px";
var outer = document.createElement('div');
outer.style.position = "absolute";
outer.style.top = "0px";
outer.style.left = "0px";
outer.style.visibility = "hidden";
outer.style.width = "200px";
outer.style.height = "150px";
outer.style.overflow = "hidden";
outer.appendChild(inner);
document.body.appendChild(outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if (w1 == w2) w2 = outer.clientWidth;
document.body.removeChild(outer);
return (w1 - w2);
}
var htmlpadding = scrollCompensate();
The correct answer is in this post marked as accepted:
CSS media queries and JavaScript window width do not match
This is the correct code:
function viewport() {
var e = window, a = 'inner';
if (!('innerWidth' in window )) {
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}
Discovered a very hacky solution... by adding this before my alerts in test2.js, I get the proper width:
var p = $('body').append('<p style="height: 100%; width: 100%;"></p>');
alert(p.width());
$('body').remove('p');
And consequently, all of the alerts now have the proper width. I also don't even need overflow-y in the CSS if I do it this way. Curious why this solves it...
The real answer should be keeping the HTML and CSS as is, then using document.getElementById('scroll').clientWidth. Using clientWidth gets the viewable area minus the scrollbar width.
The correct width of the page is given by $(document).width().
Your problem is that you're using a scroll within the div (overflow: scroll).
Using $(document).width() the returned value is already discounting the visible width of the scroll, but how do you put a scroll within the div value returned is no longer the same.
As the width of the scroll is not standard and varies from system to system and browser to browser, it is difficult to solve.
I suggest you remove the scroll of the div and let the browser manage this by default in the body, then yes you have the correct width.

Getting scroll bar width using JavaScript [duplicate]

This question already has answers here:
How can I get the browser's scrollbar sizes?
(25 answers)
Closed 5 years ago.
The following HTML will display a scroll bar on the right inside edge of div.container.
Is it possible to determine the width of that scroll bar?
<div class="container" style="overflow-y:auto; height:40px;">
<div class="somethingBig"></div>
</div>
This function should give you width of scrollbar
function getScrollbarWidth() {
// Creating invisible container
const outer = document.createElement('div');
outer.style.visibility = 'hidden';
outer.style.overflow = 'scroll'; // forcing scrollbar to appear
outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps
document.body.appendChild(outer);
// Creating inner element and placing it in the container
const inner = document.createElement('div');
outer.appendChild(inner);
// Calculating difference between container's full width and the child width
const scrollbarWidth = (outer.offsetWidth - inner.offsetWidth);
// Removing temporary elements from the DOM
outer.parentNode.removeChild(outer);
return scrollbarWidth;
}
Basic steps here are:
Create hidden div (outer) and get it's offset width
Force scroll bars to appear in div (outer) using CSS overflow property
Create new div (inner) and append to outer, set its width to '100%' and get offset width
Calculate scrollbar width based on gathered offsets
Working example here: http://jsfiddle.net/slavafomin/tsrmgcu9/
Update
If you're using this on a Windows (metro) App, make sure you set the -ms-overflow-style property of the 'outer' div to scrollbar, otherwise the width will not be correctly detected. (code updated)
Update #2
This will not work on Mac OS with the default "Only show scrollbars when scrolling" setting (Yosemite and up).
offsetWidth includes width of scroll bar and clientWidth doesn't. As rule, it equals 14-18px. So:
let scrollBarWidth = element.offsetWidth - element.clientWidth;
That will return 0 if the element doesn't currently have a scroll bar, so here's a simple function which computes the browser's scroll bar width by creating a temporary element that has a scroll bar:
function getScrollBarWidth() {
let el = document.createElement("div");
el.style.cssText = "overflow:scroll; visibility:hidden; position:absolute;";
document.body.appendChild(el);
let width = el.offsetWidth - el.clientWidth;
el.remove();
return width;
}
I think this will be simple and fast -
var scrollWidth= window.innerWidth-$(document).width()
If the child takes the full width of the container excluding scrollbar (the default), then you can subtract the widths:
var child = document.querySelector(".somethingBig");
var scrollbarWidth = child.parentNode.offsetWidth - child.offsetWidth;
If you use jquery.ui, try this code:
$.position.scrollbarWidth()
I've used next function to get scrollbar height/width:
function getBrowserScrollSize(){
var css = {
"border": "none",
"height": "200px",
"margin": "0",
"padding": "0",
"width": "200px"
};
var inner = $("<div>").css($.extend({}, css));
var outer = $("<div>").css($.extend({
"left": "-1000px",
"overflow": "scroll",
"position": "absolute",
"top": "-1000px"
}, css)).append(inner).appendTo("body")
.scrollLeft(1000)
.scrollTop(1000);
var scrollSize = {
"height": (outer.offset().top - inner.offset().top) || 0,
"width": (outer.offset().left - inner.offset().left) || 0
};
outer.remove();
return scrollSize;
}
This jQuery-based solutions works in IE7+ and all other modern browsers (including mobile devices where scrollbar height/width will be 0).
Here's an easy way using jQuery.
var scrollbarWidth = jQuery('div.withScrollBar').get(0).scrollWidth - jQuery('div.withScrollBar').width();
Basically we subtract the scrollable width from the overall width and that should provide the scrollbar's width. Of course, you'd want to cache the jQuery('div.withScrollBar') selection so you're not doing that part twice.
Assuming container is only on page once and you are using jQuery, then:
var containerEl = $('.container')[0];
var scrollbarWidth = containerEl.offsetWidth - containerEl.clientWidth;
Also see this answer for more details.
this worked for me..
function getScrollbarWidth() {
var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>');
$('body').append(div);
var w1 = $('div', div).innerWidth();
div.css('overflow-y', 'scroll');
var w2 = $('div', div).innerWidth();
$(div).remove();
return (w1 - w2);
}

Categories

Resources