Consider a stylesheet that resizes the page as the height diminishes using media queries and transform:
#media (max-height: 620px) {
body {
transform: scale(0.95);
}
}
#media (max-height: 590px) {
body {
transform: scale(0.90);
}
}
#media (max-height: 560px) {
body {
transform: scale(0.85);
}
}
// and so on ...
The page "zooms out" as the window height diminishes, allowing the full content to be displayed on smaller screens.
If I want to support screens smaller than 560px height, I need to add more media queries.
Notice that for each 30px lost in height, we call scale with 0.05 less in the input.
Question: Is it there a way to define incremental media queries using only css?
Follow Up: If a pure css solution is not available, what would be the simplest way of accomplishing such effect in vanilla JS?
Edit: Thank you all for posting different solutions to this problem. I appreciate your help. Your answers helped me learn how to improve my code.
This is not possible using CSS alone. You can do this using JS by adding a window.onresize function to watch for resizing and scaling the body of the document. This solution also scales dynamically so you do not need to worry about breakpoints or #media queries.
function updateScale() {
let viewScale = window.innerHeight / document.documentElement.scrollHeight;
document.body.style = 'transform:scale(' + viewScale + ')';
document.documentElement.scrollHeight = window.innerHeight;
}
window.onresize = function() {
updateScale();
}
updateScale();
body {
transform-origin: 0 0;
margin: 0;
padding: 0;
overflow: hidden;
}
#block {
background-color: black;
width: 300px;
height: 4000px;
}
<div id='block'></div>
#NathanFries is correct, this isn't something that is possible with native CSS.
CSS includes viewport units for percentage-based values for your width and height, but you can't pass that onto the scale() function.
You'd then need to tie this to some resize event listener.
Here is a quick example that might accomplish what you're looking to do:
// #see https://github.com/WICG/EventListenerOptions/blob/9dcca95/explainer.md#feature-detection
// #example `elem.addEventListener('touchstart', fn, supportsPassive ? { passive: true } : false);`
var checkSupportPassiveEvents = function() {
var supportsPassive = false;
try {
var opts = Object.defineProperty({}, 'passive', {
get: function() {
supportsPassive = true;
},
});
window.addEventListener('testPassive', null, opts);
window.removeEventListener('testPassive', null, opts);
} catch (e) {}
return supportsPassive;
};
var supportsPassive = checkSupportPassiveEvents();
var mapRange = function(fn, inStart, inEnd, outStart, outEnd) {
if (outStart === void 0) {
outStart = inStart;
outEnd = inEnd;
inStart = 0;
inEnd = 1;
}
var inRange = inEnd - inStart,
outRange = outEnd - outStart;
return function(val) {
var original = fn((val - inStart) / inRange);
return outStart + outRange * original;
};
};
var linear = function(x) {
return x;
};
var minHeight = 320;
var maxHeight = 620;
var minScale = 0.45;
var maxScale = 1;
var screenHeightToScaleFactorInner = mapRange(linear, minHeight, maxHeight, minScale, maxScale);
var screenHeightToScaleFactor = function(height) {
if (height <= minHeight) {
return minScale;
} else if (height > maxHeight) {
return maxScale;
} else {
return screenHeightToScaleFactorInner(height);
}
};
window.addEventListener(
'resize',
function(e) {
var height = this.innerHeight;
this.document.body.style.transform = 'scale(' + screenHeightToScaleFactor(height) + ')';
},
supportsPassive ? { passive: true } : false
);
You may have to use vanilla JavaScript in this case.
So, each 30px is 0.05, or each 6px is 0.01 from 650px down.
It means an amount of 600px is 1 in scale and that each pixel is 0.01/6.
With all that information in mind, we can use resize event to calculate this:
window.addEventListener('resize', changeTransform); // when resize, call changeTransform
var bodyEl = document.querySelector('body');
function changeTransform() {
var scale = 1; // default scale
if (window.innerHeight < 650) { // if window height < 650px, do magic
scale = -0.83 + (0.05/30)*window.innerHeight;
}
bodyEl.style.transform = "scale(" + scale + ")"; // apply scale (1 or the calculated one)
}
Hope it can help you somehow.
For a CSS solution you can consider vh and vw unit but it won't be possible with scale since this one need a unitless value.
A different approach would be to use translateZ() and some perspective to simulate a scale animation.
Here is a basic example. The result isn't accurate as I simply want to demonstrate the trick. Run the snippet full page and adjust the window height and you will see the element scaling.
.box {
width:100px;
height:100px;
background:red;
transform:perspective(180px) translateZ(15vh);
transform-origin:top left;
}
<div class="box">
some text here
</div>
You simply need to find the correct calculation for the different values.
Related
So basically I'd like to remove the class from 'header' after the user scrolls down a little and add another class to change it's look.
Trying to figure out the simplest way of doing this but I can't make it work.
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll <= 500) {
$(".clearheader").removeClass("clearHeader").addClass("darkHeader");
}
}
CSS
.clearHeader{
height: 200px;
background-color: rgba(107,107,107,0.66);
position: fixed;
top:200;
width: 100%;
}
.darkHeader { height: 100px; }
.wrapper {
height:2000px;
}
HTML
<header class="clearHeader"> </header>
<div class="wrapper"> </div>
I'm sure I'm doing something very elementary wrong.
$(window).scroll(function() {
var scroll = $(window).scrollTop();
//>=, not <=
if (scroll >= 500) {
//clearHeader, not clearheader - caps H
$(".clearHeader").addClass("darkHeader");
}
}); //missing );
Fiddle
Also, by removing the clearHeader class, you're removing the position:fixed; from the element as well as the ability of re-selecting it through the $(".clearHeader") selector. I'd suggest not removing that class and adding a new CSS class on top of it for styling purposes.
And if you want to "reset" the class addition when the users scrolls back up:
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
$(".clearHeader").addClass("darkHeader");
} else {
$(".clearHeader").removeClass("darkHeader");
}
});
Fiddle
edit: Here's version caching the header selector - better performance as it won't query the DOM every time you scroll and you can safely remove/add any class to the header element without losing the reference:
$(function() {
//caches a jQuery object containing the header element
var header = $(".clearHeader");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
header.removeClass('clearHeader').addClass("darkHeader");
} else {
header.removeClass("darkHeader").addClass('clearHeader');
}
});
});
Fiddle
Pure javascript
Here's javascript-only example of handling classes during scrolling.
const navbar = document.getElementById('navbar')
// OnScroll event handler
const onScroll = () => {
// Get scroll value
const scroll = document.documentElement.scrollTop
// If scroll value is more than 0 - add class
if (scroll > 0) {
navbar.classList.add("scrolled");
} else {
navbar.classList.remove("scrolled")
}
}
// Use the function
window.addEventListener('scroll', onScroll)
#navbar {
position: fixed;
top: 0;
left: 0;
right: 0;
width: 100%;
height: 60px;
background-color: #89d0f7;
box-shadow: 0px 5px 0px rgba(0, 0, 0, 0);
transition: box-shadow 500ms;
}
#navbar.scrolled {
box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.25);
}
#content {
height: 3000px;
margin-top: 60px;
}
<!-- Optional - lodash library, used for throttlin onScroll handler-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
<header id="navbar"></header>
<div id="content"></div>
Some improvements
You'd probably want to throttle handling scroll events, more so as handler logic gets more complex, in that case throttle from lodash lib comes in handy.
And if you're doing spa, keep in mind that you need to clear event listeners with removeEventListener once they're not needed (eg during onDestroy lifecycle hook of your component, like destroyed() for Vue, or maybe return function of useEffect hook for React).
Example throttling with lodash:
// Throttling onScroll handler at 100ms with lodash
const throttledOnScroll = _.throttle(onScroll, 100, {})
// Use
window.addEventListener('scroll', throttledOnScroll)
Add some transition effect to it if you like:
http://jsbin.com/boreme/17/edit?html,css,js
.clearHeader {
height:50px;
background:lightblue;
position:fixed;
top:0;
left:0;
width:100%;
-webkit-transition: background 2s; /* For Safari 3.1 to 6.0 */
transition: background 2s;
}
.clearHeader.darkHeader {
background:#000;
}
Its my code
jQuery(document).ready(function(e) {
var WindowHeight = jQuery(window).height();
var load_element = 0;
//position of element
var scroll_position = jQuery('.product-bottom').offset().top;
var screen_height = jQuery(window).height();
var activation_offset = 0;
var max_scroll_height = jQuery('body').height() + screen_height;
var scroll_activation_point = scroll_position - (screen_height * activation_offset);
jQuery(window).on('scroll', function(e) {
var y_scroll_pos = window.pageYOffset;
var element_in_view = y_scroll_pos > scroll_activation_point;
var has_reached_bottom_of_page = max_scroll_height <= y_scroll_pos && !element_in_view;
if (element_in_view || has_reached_bottom_of_page) {
jQuery('.product-bottom').addClass("change");
} else {
jQuery('.product-bottom').removeClass("change");
}
});
});
Its working Fine
Is this value intended? if (scroll <= 500) { ... This means it's happening from 0 to 500, and not 500 and greater. In the original post you said "after the user scrolls down a little"
In a similar case, I wanted to avoid always calling addClass or removeClass due to performance issues. I've split the scroll handler function into two individual functions, used according to the current state. I also added a debounce functionality according to this article: https://developers.google.com/web/fundamentals/performance/rendering/debounce-your-input-handlers
var $header = jQuery( ".clearHeader" );
var appScroll = appScrollForward;
var appScrollPosition = 0;
var scheduledAnimationFrame = false;
function appScrollReverse() {
scheduledAnimationFrame = false;
if ( appScrollPosition > 500 )
return;
$header.removeClass( "darkHeader" );
appScroll = appScrollForward;
}
function appScrollForward() {
scheduledAnimationFrame = false;
if ( appScrollPosition < 500 )
return;
$header.addClass( "darkHeader" );
appScroll = appScrollReverse;
}
function appScrollHandler() {
appScrollPosition = window.pageYOffset;
if ( scheduledAnimationFrame )
return;
scheduledAnimationFrame = true;
requestAnimationFrame( appScroll );
}
jQuery( window ).scroll( appScrollHandler );
Maybe someone finds this helpful.
For Android mobile $(window).scroll(function() and $(document).scroll(function() may or may not work. So instead use the following.
jQuery(document.body).scroll(function() {
var scroll = jQuery(document.body).scrollTop();
if (scroll >= 300) {
//alert();
header.addClass("sticky");
} else {
header.removeClass('sticky');
}
});
This code worked for me. Hope it will help you.
This is based of of #shahzad-yousuf's answer, but I only needed to compress a menu when the user scrolled down. I used the reference point of the top container rolling "off screen" to initiate the "squish"
<script type="text/javascript">
$(document).ready(function (e) {
//position of element
var scroll_position = $('div.mainContainer').offset().top;
var scroll_activation_point = scroll_position;
$(window).on('scroll', function (e) {
var y_scroll_pos = window.pageYOffset;
var element_in_view = scroll_activation_point < y_scroll_pos;
if (element_in_view) {
$('body').addClass("toolbar-compressed ");
$('div.toolbar').addClass("toolbar-compressed ");
} else {
$('body').removeClass("toolbar-compressed ");
$('div.toolbar').removeClass("toolbar-compressed ");
}
});
}); </script>
I'm using a script that is resizing my .container when my window is resized. This is my page: http://cjehost.com/qt/nipt/page6.php
If you resize the browser window, you'll see the container resize but not stay centered. Is there a way to center my container? Here is my script:
// Resize the map to fit within the boundaries provided
function resize(maxWidth, maxHeight) {
var image = $('img'),
imgWidth = image.width(),
imgHeight = image.height(),
newWidth = 0,
newHeight = 0;
if (imgWidth / maxWidth > imgHeight / maxHeight) {
newWidth = maxWidth;
} else {
newHeight = maxHeight;
}
image.mapster('resize', newWidth, newHeight, resizeTime);
}
// Track window resizing events, but only actually call the map resize when the
// window isn't being resized any more
function onWindowResize() {
var curWidth = $(window).width(),
curHeight = $(window).height(),
checking = false;
if (checking) {
return;
}
checking = true;
window.setTimeout(function() {
var newWidth = $(window).width(),
newHeight = $(window).height();
if (newWidth === curWidth &&
newHeight === curHeight) {
resize(newWidth, newHeight);
}
checking = false;
}, resizeDelay);
}
$(window).bind('resize', onWindowResize);
My css:
.container {margin:0 auto;}
I would recommend really a CSS approach instead of JavaScript approach for this one. Responsive CSS with #media queries are there for this. Don't use DOM Manipulations with JavaScripts, that are really costly in the terms of performance.
CSS Centering
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
#media Queries
#media screen and (max-width: 380px) {
// Styles for Mobiles
}
#media screen and (min-width: 381px) and (max-width: 760px) {
// Styles for Tablets
}
#media screen and (min-width: 761px) {
// Styles for Desktops
}
You can find an exhaustive list online.
I managed to make this work by replacing window with .container (my container div). It's still a bit clunky - i.e. when I switch to full screen from smaller resolutions the container doesn't always resize. Here is my working code:
// Track window resizing events, but only actually call the map resize when the
// window isn't being resized any more
function onWindowResize() {
var curWidth = $('.container').width(),
curHeight = $('.container').height(),
checking = false;
if (checking) {
return;
}
checking = true;
window.setTimeout(function() {
var newWidth = $('.container').width(),
newHeight = $('.container').height();
if (newWidth === curWidth &&
newHeight === curHeight) {
resize(newWidth, newHeight);
}
checking = false;
}, resizeDelay);
}
$(window).bind('resize', onWindowResize);
$(window).resize(onWindowResize);
});
Here is a working fiddle: enter link description here
I found reference to this approach and fiddle here: enter link description here
Thanks to #LBF
I want to make an background color animation change when the user gets to the specific section.
Here is the jQuery code I wrote:
var initialColors = [];
$('section.changecolorbg').each(function(i){
initialColors[i] = $(this).css("backgroundColor");
});
$(window).scroll(function() {
$('section.changecolorbg').each(function(i){
if(isScrolledIntoView($(this))){
var bgc = initialColors[i];
$(this).parent().children('.changecolorbg').each(function(){
$(this).css("backgroundColor", bgc);
});
}
})
});
function isScrolledIntoView(elem)
{
var hT = elem.offset().top,
hH = elem.outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop() + 200;
return (wS > (hT+hH-wH))
}
The sections will have a background-color initially, this is why I saved them in a variable.
The problem with this is that it's working pretty slow. I think is that because all the checking needs to be done in the .scroll function.
Is there a way I can improve the code?
P.S. The effect I'm trying to achieve is same as on http://sfcd.com/
You can try something like this using hsl colors in CSS (hue, saturation, lightness) and deriving the hue value from the window.scrollY position:
var body = document.getElementsByTagName('body')[0];
function changeHue() {
var hue = (window.scrollY / 20);
body.style.backgroundColor = 'hsl('+hue+', 100%, 50%)';
}
window.addEventListener('scroll', changeHue, false);
body {
background-color: hsl(0,100%,50%);
}
div {
height: 10000px;
}
<div></div>
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 am developing a bunch of small web applications that have an unknown window size as target. To solve this problem, I am developing very large layouts and scaling them according to the window size.
My solution however has an inconvenience. When I resize everything, things get a little bit out of place (mainly when scaling text) and it is noticeable. My code is very simple, everything in my page is absolutely positioned so I just get the scaling factor and apply it to all the positions and width / height of every div/img/span/input in the page. The code is as follows:
function resize()
{
var wh = $(window).height();
var h = maxHeight;
var ww = $(window).width();
var w = maxWidth;
var wProp = ww / w;
var hProp = wh / h;
if (wProp < hProp) prop = wProp;
else prop = hProp;
if (prop > 1) prop = 1;
console.log(prop);
$("div").each (applyNewSize);
$("img").each (applyNewSize);
$("span").each (applyNewSize);
$("input").each (applyNewSize);
}
//this is run when the page is loaded
function initializeSize (i)
{
this.oX = $(this).position().left;
this.oY = $(this).position().top;
this.oW = $(this).width();
this.oH = $(this).height();
if ($(this).css("font-size") != undefined)
{
this.oFS = Number($(this).css("font-size").split("px")[0]);
}
}
function applyNewSize (i)
{
if (this.oFS != undefined) $(this).css("font-size", Math.round(this.oFS * prop) + "px");
$(this).css("left", Math.round(this.oX * prop) + "px");
$(this).css("top", Math.round(this.oY * prop) + "px");
$(this).width(Math.round(this.oW * prop));
$(this).height(Math.round(this.oH * prop));
}
This problem has been tormenting me for the past week. Do you have any workaround or solution for this?
I recommend you to read about Responsive Web design.
It works putting % instead the exact pixels :
<div class="container">
<section>
THIS IS THE SECTION
</section>
</div>
CSS::
.container{
width: 80%; // 80% instead pixels
background: gainsboro;
border: 3px inset darkgrey;
height: 200px;
margin:auto;
text-align:center;
}
section{
width: 80%; // 80% instead pixels
height: 80%; // 80% instead pixels
background: darkgrey;
margin:auto;
}
Then you can use media queries as well, to reallocate the blocks or applying different styles on different widths :
example tutorial : http://css-tricks.com/css-media-queries/