I'm trying to make my own scroll bar, and so far it's working fine, for this small exception.
When I reach the bottom of the page, the bar handle goes under the viewport.
Gif of what's happening:
I know it has to do with the CSS, but I'm unsure on how to set it correctly. Foundation's .off-canvas-content has a class added named .full-height, and the height property is added so that the scroll bar won't be tied to that element.
The scroll bar markup is added to div.content, which is where all the remaining content will be.
I'm trying to get the handle bar to stop at the bottom of the container, when the user has scrolled all the way of the bottom of the document, but haven't found a way to do this correctly.
CSS:
.scroll-container {
position: fixed;
right: 50px;
top: 0;
height: 100%;
width: 7.5px;
background-color: rgba(55,55,55,.3);
}
.scroll-bar {
position: relative;
top: 0;
height: 20%;
width: 100%;
background-color: #6A1B9A;
}
.full-height {
height: 100vh;
min-height: 100vh;
}
.content {
float: left;
width: 100%;
height: 100%;
display: block;
padding: 10px 20px;
overflow-y: scroll;
}
JS:
(function($) {
$.fn.scroller = function() {
var self = this,
scrollBarDrag = false,
docHeight = $(document).height();
var scrollContainer = document.createElement('div'),
scrollBar = document.createElement('div');
scrollContainer.className = 'scroll-container';
scrollBar.className = 'scroll-bar';
scrollContainer.appendChild(scrollBar);
self[0].appendChild(scrollContainer);
self.on('scroll', function() {
var top = $(this).scrollTop();
setScrollBarTop(top);
});
function setScrollBarTop (top) {
scrollBar.style.top = top + 'px';
}
};
})(jQuery);
I tried using plugins for this, but they don't simulate the scroll bar as intended (missing mouse wheel click and drag to scroll), so I decided to make my own, lightweight version of it. Any suggestions about using plugins, albeit appreciated, will be disregarded and not accepted as an answer.
With absolute positioning:
I think you forgot to account for the scrollbar's height. Lets say the scrollbar is 100px tall and your page is 500px tall, you are only able to move the scrollbar by 400px, not all 500.
Find out the difference between your scrollbar height and the document height, find the ratio of how they compare, and apply that to your new scrollbar position.
havent tested it, but something like;
var heightToWorkWith = docHeight - scrollBarHeight;
var ratio = heightToWorkWith / docHeight;
function setScrollBarTop (top) {
scrollBar.style.top = (top * ratio) + 'px';
}
Have found a solution regarding this, was quite a bit of trial and error, but managed to find it in the end. Hope it can be of use to some of you.
Edited it to a more revised version.
self.on('scroll', function() {
elHeight = self.height();
docHeight = $(document).height();
var sTop = self[0].scrollTop;
var sHeight = self[0].scrollHeight;
var sBHeight = $(scrollBar).height();
var ratio = (elHeight - $(scrollBar).height()) / elHeight;
var currentPosY = (sTop / (sHeight - docHeight)) * 100;
scrollBar.style.top = (currentPosY * ratio) + '%';
});
You can get scroll ratio by doing this:
(thumbHeight / containerHeight) + 1
containerHeight is not the scroll area height, but the actual overflow: hidden container.
When you get the scrollTop value just multiply it with your ratio. Like this:
thumbPosition.top = el.scrollTop * ratio + 'px';
Related
I have an image in a div and I want the image to stay centered at all times.
If the width of the image is wider than the screen, then I want the image to expand to the width of the view port. And if the image is shorter than the height of the view port then I want it to expand to the height of the view port.
In my code, when I expand the width, the height expands automatically, which is great since I don't have to calculate it. The height does the same thing. When the height is expanded, the width stays proportional.
However, if the width changes in such a way that the height is now smaller than then view port, then I need to check the height and bring it back up to the view port height (which should expand the width again but it doesn't). When I have to change both height and width at the same time, the automatic proportioning doesn't work. If I do one or the other, it does work.
How can I accomplish this so they can both be changed and work without distorting the image?
my code:
inner_width = $(window).innerWidth();
inner_height = $(window).innerHeight();
if (inner_width < original_pic_width ) {
$(pic).css({'width': original_pic_width});
}
else {
$(pic).css({'width' : inner_width });
}
if (inner_height < original_pic_height){
$(pic).css({'height': original_pic_height});
}
else {
$(pic).css({'height' : inner_height });
}
CSS contain is pretty nice.
$("div").css({
backgroundImage: "url(" + $("img").prop('src') + ")",
backgroundSize:"contain",
backgroundRepeat: "no-repeat"
});
div { width:200px; height:200px; border:1px solid red;}
div img { display:none }
<div>
<img src="http://www.somebodymarketing.com/wp-content/uploads/2013/05/Stock-Dock-House.jpg"/>
</div>
<script src="https://code.jquery.com/jquery-2.2.3.min.js"
integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo="
crossorigin="anonymous"></script>
Here is a possible solution (not sure to understand clearly what you want though). Note that I'm not absolutely sure that the centering method is cross-browser.
var div = $("div");
var img = $("img");
var imgw = img.width();
var imgh = img.height();
var imgr = imgw / imgh;
var sizes = [300, 120];
var i = 0;
setInterval(function () {
div.width(sizes[i]);
i = (i + 1) % 2;
adjust();
}, 1000);
function adjust () {
var divw = div.width();
var divh = div.height();
var divr = divw / divh;
if (divr < imgr) {
img.width("100%");
img.height("auto");
} else {
img.width("auto");
img.height("100%");
}
}
div {
position: relative;
}
img {
display: block;
position: absolute;
top: 0; bottom: 0;
right: 0; left: 0;
margin: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width:120px;height:120px;border:10px solid #5900CC;">
<img style="width:100%;" src="http://i.stack.imgur.com/jKXi2.jpg" />
</div>
If you set both height and width... both dimensions, height and width will be set.
It should be enough to set just one dimension if you set the width=viewport's width if it's horizontal (width>height) or the height=viewport's height if it's vertical.
Find which dimension you have to change and change that one only. You can do that by checking the difference between the image's width and the window's innderWidth, and the difference between the image's height and the window's innerHeight. Whichever difference is greater is the one you need to change only. That should take care of the other dimension without having to resize both.
I have created a magnifier in pure js. What I discovered in needing to translate the mouse position of a div relative to its parents is that in calculating the top for the overlaying magnifier div, the offsetTop works differently than the offsetLeft. After adjusting for what should be the top, I need to subtract the whole container div's offsetHeight.
The line in the code in question is this:
magnifier.style.top = yPosition - container.offsetHeight + "px";
Why do I need to subtract container.offsetHeight?
I know I've read something regarding this, but can't find it.
Disclaimers This code is working. I am asking so I (and those following) can understand how the box model works.
I know there are jQuery alternatives that are more cross browser reliable. I like to code it myself so that I can learn how it all works. If you see something which is not compatible for a modern browser, feel free to comment.
Lastly, For anyone using this, I removed code from this example to adjust for transforms. For example, if the wrapper has a transform: translate(-50%, 0); to center the wrapper horizontally, you will need to add the resulting amount of the translation (which translates to the wrapper's left position) back into the calculation.
I have created a jsfiddle here. I left more comments in the Fiddle as to methodology if anyone is interested.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="../css/ms.js"></script>
<style type="text/css">
/********************/
body {
background-color: #FFF;
margin-left: 30px;
margin-top: 10px;
}
.wrapper {
position: absolute;
left: 100px;
}
#container {
width: 527px;
height: 450px;
border: 5px black solid;
overflow: hidden;
background-color: #F2F2F2;
cursor: pointer;
}
#image {
width: 527px;
height: 450px;
}
#magnifier {
width: 250px;
height: 250px;
overflow:hidden;
position:relative;
z-index: 1000;
border: solid 1px;
}
#magnifier img {
position: absolute;
}
</style>
</head>
<body>
<div class="wrapper" id="wrapper">
<div id="container">
<img id="image" src="../docs/grade-2/jpg/g2-bb-saints-francis.jpg">
<div id="magnifier" class="magnifier">
<img id="imagecopy">
</div>
<br>
</div>
<input type="button" value="Zoom" onClick="initmagnifier('magnifier', 'image', 'imagecopy');"><br>
</div>
<script>
function initmagnifier(magnifier, image, imagecopy){
var magnifier = document.getElementById("magnifier");
var container = document.getElementById("container");
var wrapper = document.getElementById("wrapper");
var img = document.getElementById(image);
var imgcopy = document.getElementById(imagecopy);
var zoom = 2;
container.addEventListener("mousemove",
function(e){
movemagnifier(e, img, imgcopy, magnifier, container, wrapper, zoom)
}, false);
var src = img.src;
imgcopy.src = src;
var src2 = imgcopy.src;
imgcopy.height = img.height * zoom;
imgcopy.width = img.width * zoom ;
}
function movemagnifier(e, img, imgcopy, magnifier, container, wrapper, zoom) {
// to get the left & top of the magnifier
// position needs to be adjusted for WRAPPER & CONTAINER top and left
// gets the top and left of the container
var containerPosition = getPosition(e.currentTarget);
// adjust out the CONTAINER's top / left
// Then takes 1/2 the hight of the MAGNIFIER and subtracts it from the MOUSE position to center MAGNIFIER around the MOUSE cursor
var xPosition = e.clientX - containerPosition.x - (magnifier.clientWidth / 2);
var yPosition = e.clientY - containerPosition.y - (magnifier.clientHeight / 2);
magnifier.style.left = xPosition + "px";
magnifier.style.top = yPosition - container.offsetHeight + "px";
// Adjust for zoom
// adjust the MAGNIFIER's top/left at an equal pace to the zoom amount
var yTravel = (e.clientY - containerPosition.y ) * (zoom - 1);
var yimgPosition = -(yPosition - container.clientTop + yTravel);
imgcopy.style.top = yimgPosition + "px";
var xTravel = (e.clientX - containerPosition.x) * (zoom - 1); // * 1.5
var ximgPosition = -(xPosition + xTravel);
imgcopy.style.left = ximgPosition + "px";
console.log('****');
console.log(e.clientY); // MOUSE POSTION
console.log(containerPosition.y);
console.log(wrapper.offsetTop);
console.log(wrapper.clientHeight);
console.log(container.offsetTop);
console.log(container.clientHeight);
console.log(yPosition);
console.log(container.offsetHeight);
console.log(magnifier.style.top);
}
function getPosition(element) {
var xPosition = 0;
var yPosition = 0;
// element is the CONTAINER
// This calculates the postion of the element (CONTAINER) TOP & LEFT relative to ALL parents
while (element) {
// if transform: translate in place for x and y,
// add it back as it skews the offsetLeft offsetTop values by the translate amount
xPosition += ((element.offsetLeft) - element.scrollLeft);
yPosition += ((element.offsetTop) - element.scrollTop);
element = element.offsetParent;
}
return { x: xPosition, y: yPosition };
}
</script>
</body>
</html>
It took me longer than I care to admit, but I have found the reason. In your fiddle you position the #magnifier-element relative, which means you have to move it from its 'natural' position, which is below the image inside the container.
So with every move you have to compensate for this, by pulling the #magnifier to the top/left position of the container, the left position already matches, but the 'natural' top position of the #magnifier is the full height of the container, as you calculate from the top/left position of the #container, you need to subtract the #container height.
A simple fix is to add position: relative to the #container and change position: relative on the #magnifier to position: absolute.
This will give you the expected coordinate system for the #magnifier as top: 0; left: 0 for the absolute positioned element is the top left corner of the its relative parent (the first positioned parent element, in this case #container).
a working example without the need to to subtract container.offsetHeight.
While I'm at it, you may want to look into the Element.getBoundingClientRect function, as you can get all information you need to determine the position in a single call.
I'm trying to use jQuery to set the height of a div so that it takes up the entire window + the height of a header (so that you can scroll the header off the page) but no more than that. I would think the height of the div would be the height of the window + the height of the header I'm trying to hide.
When I set the div to window height, however, it creates overflow. Here's the rough code:
var $body = $("#body"),
$container = $("#container"),
$window = $(window),
$content = $("#mainContent"),
$header = $("#header"),
bodyHeight = window.innerHeight + $header.height();
$body.css("height", window.innerHeight);
$container.css("height", bodyHeight);
div {
display: block;
width: 100%;
margin: 0;
}
#body {
overflow-y: scroll;
}
#container {
overflow-y: hidden;
}
#header {
overflow: hidden;
}
#navbar {
height: 10px;
background-color: brown;
}
#mainContent {
height: 200px;
overflow-y: scroll;
}
#contentP {
height: 400px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="body">
<div id="container">
<div id="header">
<h1>Header</h1>
</div>
<div id="navbar">
</div>
<div id="mainContent">
<p id="contentP">This is content</p>
</div>
</div>
</div>
Why is there overflow if the div is sized to fit in the window?
EDIT: So far, answers haven't helped. This is the site I'm working on. It's joomla. I want the nav bar to lock at the top of the screen.
$(document).ready(function() {
//Declare some variables
var $window = $(window),
$body = $(".body"),
$mainContent = $("#maincontent"),
headerGap = parseFloat($("#headerimg").css("margin-top")),
headerHeight = headerGap + $("#header").height() + parseFloat($("#navbar").css("margin-top")),
navbarHeight = $("#navbar").height(),
footerHeight = $("#footer").height();
//set the height of the body and the maincontent
resizePage();
//Set the listeners for resizing and scrolling
$window.resize(resizePage);
$window.scroll(scrollHandler);
//When you scroll, see if the navbar is at the top. Set maincontent overflow
//to scroll when the navbar is at the top of the window. Set it to hidden otherwise
function scrollHandler() {
if ($window.scrollTop() < headerHeight - 1) {
$mainContent.css("overflow", "hidden");
} else {
$mainContent.css("overflow", "auto");
}
}
//Set the body and the mainContent to be the correct sizes when the window size is changed. In theory, the body should be:
// windowHeight + headerHeight
// maincontent should be:
// windowHeight - (headerHeight + navbarHeight + footerHeight)
// But that doesn't quite work out.
function resizePage() {
//Deal with the changing CSS due to media queries
if ($(window).width() > 768) {
headerGap = parseFloat($("#headerimg").css("margin-top"));
headerHeight = headerGap + $("#header").height() + parseFloat($("#navbar").css("margin-top")) - 1;
$(".nav.menu.nav-pills").css("width", "92.5%");
}
else {
headerHeight = $("#header").height();
$(".nav.menu.nav-pills").css("width", $window.width());
}
//The header and navbar height change at certain sizes, so grab them again to be safe.
navbarHeight = $("#navbar").height();
footerHeight = $("#footer").height();
var windowHeight = $window.height(),
contentHeight = windowHeight - (footerHeight + navbarHeight);
//if we account for headerHeight too, maincontent is too big
resizeContent(contentHeight);
resizeBody(windowHeight);
}
//The body should take up the whole height of the window, plus the header
//and margin heights at the top. This way, you scroll to the navbar.
// But it doesn't work this way.
// -7 and -27 are from eyeballing it.
function resizeBody(windowHeight) {
if($window.width() > 728) {
$body.css("height", windowHeight - 7);
}
else {
$body.css("height", windowHeight - 27);
}
}
// The content should go from the bottom of the navbar to the bottom of the footer.
//
function resizeContent(contentHeight) {
$mainContent.css("top", (headerHeight + navbarHeight));
$mainContent.css("bottom", (0 - headerHeight));
//For the background slideshow on the Furniture page
// Again, + 5 was eyeballed
$("div.moduletable").css("height", contentHeight + 5);
if ( (contentHeight + 5) < ($(window).width()) /2 ) {
$(".wk-slideshow img").css("width", "100%");
$(".wk-slideshow img").css("height", "auto");
}
else {
$(".wk-slideshow img").css("height", contentHeight + 5);
$(".wk-slideshow img").css("width", "auto");
}
}
});
It works for a lot of sizes, but one you get to small resolutions it falls apart.
EDIT 2: I was able to get the effect I was going for by adding another div. I set the body to be the height of the window and the new div to be the size of the body + the height of the header. The body has "overflow-y: scroll". The container would have "overflow-y: hidden" (See updated snippet). This doesn't totally answer my question, but at least it helps?
I've taken a look at your code and altered it. Try this and see if this is what you're looking for.
In my example i'm looking for the element by getElementById and then I set it's style.height to window.innerHeight - 10px without taking the 10px it wouldn't show the border fully on the page. So you just remove 10px's. The example has been tested on different screen sizes.
Javascript example:
function autoResizeDiv() {
document.getElementById('body').style.height = window.innerHeight - 10 + 'px';
console.log(window.innerHeight - 10 + 'px');
}
window.onresize = autoResizeDiv;
autoResizeDiv();
#body {
display: block;
border: 5px solid black;
}
body {
overflow: hidden;
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="body">
</div>
The following worked for me:
$(".body").height($(window).height());
I figured out the biggest problem. I was using some absolutely positioned elements without giving a parent any other position. This made things show up wonky when I was trying to size other things. I also needed to have an extra div as a container for all the content on the page that would be the height of the window + the height of the header.
Thanks to everyone who answered, it helped!
I have three blocks, I want them positioned at the bottom always, regardless of the viewport height, and when there's not enough height to show all of it, I want them to hide from the bottom, NOT the top.
I tired a flexbox solution: http://jsbin.com/kutipequxe/1/edit?css,output
.. it almost works, except on low resolutions, the blocks hide from top, bottom remains visible.
I also tried another solution: http://jsbin.com/ruhigijeba/1/edit?css,output
.. well this keeps the top always visible, but just hides the bottom altogether, including the other two blocks.
I even tried a JS solution:
var vh = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
var topHeight = document.getElementById('top').offsetHeight;
console.log('Viewport Height: ' + vh);
function getHeight(element) {
console.log(document.getElementsByClassName(element));
var offsetHeight = document.getElementsByClassName(element)[0].offsetHeight;
console.log('offsetHeight: ' + offsetHeight);
var marginTop = vh - (topHeight + offsetHeight);
console.log('marginTop: ' + marginTop);
document.getElementsByClassName(element)[0].style.marginTop = marginTop + "px";
}
getHeight("card-1");
getHeight("card-2");
getHeight("card-3");
... but it still hides the blocks from top!
try it with CSS media queries:
At the end of your CSS just add
#media screen and (max-height: 120px) {
div#top {
display: none;
height: 0px;
}
#main {
height: 100vh;
}
}
[edit] appearently thats not what oyu were asking for.
so... in your second jsbin example, add this to your .cards class:
position: sticky;
bottom: 0;
and to your #cards id:
overflow: hidden;
http://jsbin.com/zijedofija/1/
it does not work on chrome 35+ though: Why doesn't position: sticky work in Chrome?
my best bet would be to use a jquery plugin for chrome: https://github.com/filamentgroup/fixed-sticky
Ended up using Javascript and CSS media queries to achieve the desired results:
var vh = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
var topHeight = document.getElementById('top').offsetHeight;
function getHeight(element) {
var elementHeight = document.getElementsByClassName(element)[0].offsetHeight;
var offsetTop = vh - (topHeight + elementHeight);
var cardsContainerHeight = document.getElementById('cards').offsetHeight;
if (elementHeight < cardsContainerHeight) {
document.getElementsByClassName(element)[0].style.top = offsetTop + "px";
}
}
var resize = function(event) {
getHeight("card");
}();
I have this code for moving the box using .scrollTop. Using this i code i was able to move the box from bottom to top, is there any other way to control the speed of scrolling every 100 pixel?
Here's my jquery:
$(document).ready(function () {
$(window).scroll(function () {
var x = $(document).scrollTop();
var dh = $(window).innerHeight();
var move = x / 100 * 100;
console.log(x);
$('.box').css('bottom', move);
}
});
});
and the css:
body {
height: 2000px;
}
.box {
width: 50px;
height: 50px;
background: #f00;
bottom: 0;
position: fixed;
}
Is there a way to do this? Thanks in advance guys. Have a nice day.
Not sure if this is exactly what you are getting at, if not, please be more specific as to what you are asking for. That said....
var move = x / 100 * 100;
Just change the numbers in the denominator. It alters the rate of scroll.