How can I change the height value from 100 pixels to a percentage value? Lets say 50%. I'm fairly new to javascript...
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$(".item-info-overlay p").dotdotdot({
ellipsis:"...",
wrap:"word",
height: 100,
after:"a.readmore",})
});
</script>
Rather than modifying the dotdotdot code, it might be simpler to calculate a pixel value based on your percentage and pass that pixel value to dotdotdot.
For example:
// define your desired percentage
var percentage = 50;
jQuery(function() {
// calculate pixel height based on your percentage
var dot_height = jQuery('div#container').height() * (percentage / 100);
jQuery("div#text").dotdotdot({
ellipsis: "...",
height: dot_height,
wrap: "word",
after: "a.readmore",
watch: "window"
});
});
div#container {
height: 150px;
background-color: #CCC;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jQuery.dotdotdot/1.7.2/jquery.dotdotdot.min.js"></script>
<div id="container">
<div id="text">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi commodo, ipsum sed pharetra gravida, orci magna rhoncus neque, id pulvinar odio lorem non turpis. Nullam sit amet enim. Suspendisse id velit vitae ligula volutpat condimentum. Aliquam erat
volutpat. Sed quis velit. Nulla facilisi. Nulla libero. Vivamus pharetra posuere sapien. Nam consectetuer. Sed aliquam, nunc eget euismod ullamcorper, lectus nunc ullamcorper orci, fermentum bibendum enim nibh eget ipsum. Donec porttitor ligula eu
dolor. Maecenas vitae nulla consequat libero cursus venenatis. Nam magna enim, accumsan eu, blandit sed, blandit a, eros. Quisque facilisis erat a dui. Nam malesuada ornare dolor.
Read More
</div>
</div>
If you're building a responsive site or your container is fluid, you can apply this same logic inside of a throttled resize handler.
Related
Considering that components such as dialogs, modals, tooltips, etc. should be of higher stacking index than any other elements in an HTML page, I placed these components in an immediate sibling of root element where all the other elements are placed. React developers will quickly recognize this and they'll know that I'm trying to use React Portals. You can visualize it here:
<body>
<div id="root">
// ----- other elements -----
<div id="supposed-parent" />
// ----- other elements -----
</div>
<div id="dialog-container">
<div id="supposed-child" />
</div>
</body>
So, how can I position #supposed-child next or beside #supposed-parent? Any help would be appreciated.
I don't think this is possible with a pure css. But with a little script we can achieve this. Take the offset-left and top of the supposed-parent and apply the same to the supposed-child. The child should be absolute positioned element. Check the below sample and It hope this will be useful for you.
Even though the supposed-child(yellow box) is independent of the supposed-parent, It will be always align with the top-left of the supposed-parent.
function offsetCalculate(){
var parentTop = $('#supposed-parent').offset();
var parentLeft = $('#supposed-parent').offset();
$('#supposed-child').css({
'top':parentTop.top,
'left': parentLeft.left
});
}
$(document).ready(function () {
offsetCalculate();
});
$(window).resize(function(){
offsetCalculate();
});
#supposed-child{
position: absolute;
background: yellow;
border-radius: 5px;
padding: 10px;
z-index: 999;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="root">
<h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer dolor libero, euismod et nisl eu, imperdiet elementum neque. Praesent aliquet non tellus sed blandit. Ut vitae velit eget turpis ornare convallis. Quisque nec felis eget mi vestibulum luctus eu non dui.</h1>
<div id="supposed-parent">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer dolor libero, euismod et nisl eu, imperdiet elementum neque. Praesent aliquet non tellus sed blandit. Ut vitae velit eget turpis ornare convallis. Quisque nec felis eget mi vestibulum luctus eu non dui. Pellentesque eget commodo tellus. Curabitur a dolor est. Integer dapibus lectus nec mi luctus, ac ornare ex auctor. Donec vel nisi nulla. Mauris maximus egestas nunc ut egestas. Suspendisse id leo nec elit consectetur interdum. Ut purus nibh, tristique quis est vel, ultrices blandit nibh. Aenean nibh justo, mattis sed vulputate quis, efficitur eu mauris. Sed vel vulputate metus, et dictum arcu. In ornare nisl vitae purus elementum, quis egestas dolor volutpat. In velit nisi, posuere in urna non, feugiat luctus enim.
</div>
</div>
<div id="dialog-container">
<div id="supposed-child" >This is a popup</div>
</div>
I can see lots of ways to do the opposite of what i am trying to achieve but noting for what I need.
I have a fixed header that is 100px tall. I want it to scroll away with the rest of the page when a specified div hits the header or it is 100px from the top of the screen.
I had was adding a scroll class to the header which was literally just making it position absolute, causing the header to jump of screen. I then translateY'd it back into view, this didn't work the same across all screen sizes.
My next idea is maybe keeping it fixed but adding a negative transformY to the header, dependent on scroll position. This would achieve the same effect I am going for but i'm not too sure how to achieve this.
If you need any more information then i am happy to provide it.
edit:
Here are some screen shots:
from the top of the page:
Then this is where i want the header to become un-fixed and scroll with the rest of the page:
Check out my solution. Hope this helps.
const headerEl = document.querySelector('header')
const targetEl = document.querySelector('#target')
const targetTopPos = targetEl.getBoundingClientRect().top
let isHeaderFixed = true
document.onscroll = () => {
const targetTopOffset = targetEl.getBoundingClientRect().top
if (isHeaderFixed && targetTopOffset < 100) {
headerEl.style.position = 'absolute'
headerEl.style.top = `${targetTopPos - 100}px`
isHeaderFixed = !isHeaderFixed
}
if (!isHeaderFixed && targetTopOffset >= 100) {
headerEl.style.position = 'fixed'
headerEl.style.top = '0px'
isHeaderFixed = !isHeaderFixed
}
}
body {
padding: 0;
margin: 0;
position: relative;
}
header {
position: fixed;
height: 100px;
width: 100%;
background: lightblue;
}
.content {
line-height: 100px;
}
.target {
width: 100%;
background: red;
}
<header>
Custom header
</header>
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam suscipit tellus urna, ut tristique felis lobortis sed. Phasellus maximus at magna mattis vulputate. Pellentesque tempor, urna vitae congue pellentesque, est mauris faucibus nulla, vitae molestie leo purus a leo. Curabitur ut mi ac sem finibus consectetur a blandit massa. Morbi ornare tincidunt ipsum, et accumsan erat fringilla a. Cras egestas, nibh vel condimentum ultrices, nunc ipsum tempus magna, eu ullamcorper tortor magna id lacus. Morbi euismod lacus a ligula rutrum, in aliquet lectus blandit. Nam placerat sollicitudin lectus eu ornare. Etiam placerat diam eget magna blandit rutrum. Nulla et luctus massa. Sed sit amet mauris in magna tincidunt consequat. Proin mattis sit amet arcu a gravida. Nullam tempor urna nec dolor convallis consectetur sit amet a elit. Cras ut odio nec lacus efficitur porta nec sit amet justo.
</div>
<div id="target" class="target">target</div>
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam suscipit tellus urna, ut tristique felis lobortis sed. Phasellus maximus at magna mattis vulputate. Pellentesque tempor, urna vitae congue pellentesque, est mauris faucibus nulla, vitae molestie leo purus a leo. Curabitur ut mi ac sem finibus consectetur a blandit massa. Morbi ornare tincidunt ipsum, et accumsan erat fringilla a. Cras egestas, nibh vel condimentum ultrices, nunc ipsum tempus magna, eu ullamcorper tortor magna id lacus. Morbi euismod lacus a ligula rutrum, in aliquet lectus blandit. Nam placerat sollicitudin lectus eu ornare. Etiam placerat diam eget magna blandit rutrum. Nulla et luctus massa. Sed sit amet mauris in magna tincidunt consequat. Proin mattis sit amet arcu a gravida. Nullam tempor urna nec dolor convallis consectetur sit amet a elit. Cras ut odio nec lacus efficitur porta nec sit amet justo.
</div>
I should by default make .header {position: absolute} and add this class to css (not to element yet):
.header.active {
position: fixed;
top: 0;
left: 0;
width: 100%;
}
Then understand when we need to carry this event on header. JS will help:
var targetElement = document.querySelector( YOUR TARGET ELEMENT ),
header = document.querySelector('.header');
window.onscroll = function(event){
if ( targetElement.offsetTop > window.pageYOffset ) {
header.classList.add('active');
} else {
header.classList.remove('active');
}
}
Target element is element which when you want to reach it, header will be fixed.
If you need
I'm trying to create an overlay that attaches itself to an existing DOM node and covers its entire content area. This should work regardless of whether this node is the body of the page or some deeply nested div. It's key that the layout of the page that I am overlaying should not change. Eventually, my code will run as a browser extension on top of existing html pages.
I am encountering a problem in the very simple case where I am trying to overlay a page with text (or anything that takes space) directly nested within the document body. I have no choice but to append my overlay div as another child node of the body and set its position to absolute and its width/height to 100%. Of course, in the case where the body is statically positioned (default), my div will size to the viewport and not the body's content. If content overflows, my overlay won't cover all of it :\.
All other answers suggest setting the position of the parent div (the body in my case) to define it as the positioning context. I can't do this, however. Changing the position of the document body to 'relative', for example, could change the layout of the content of the body, and defeats the purpose of an unobtrusive overlay. What to do?
Extension-specific suggestions are welcome. For reference, the extension will be for Chrome.
Here's a jsfiddle with a hypothetical page that I have to overlay. Note that although the original page is strangely formatted, my overlay cannot change it.
<body>
<style>
.overlay {
position: absolute;
top: 0px;
left: 0px;
width: 100%;
height: 100%
/*some magic I am unaware of*/
}
</style>
<!-- begin original document (stupid hypothetical scenario) -->
<div style="position:absolute;top:0px;width:100%;height:100%;background-color:red;">
<!-- this div is part of the original html document I want to overlay.
It should behave as it did originally, i.e size to the viewport of the document-->
</div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam id tellus vehicula, tincidunt est fermentum, hendrerit dui. Nullam lacinia, justo sed porta hendrerit, nisl quam blandit nunc, ut imperdiet nibh metus in ante. Pellentesque viverra egestas
nulla eu dictum. Aliquam ac accumsan leo. Integer ut tellus odio. Duis blandit venenatis venenatis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum vel lorem egestas, tincidunt sem vel, venenatis
ipsum. Donec vitae blandit nibh. Curabitur cursus nunc arcu, id tempor massa gravida ut. Integer vulputate libero in placerat vestibulum. Duis quis turpis vel lectus venenatis rhoncus. Sed congue est consequat, dapibus odio sit amet, sollicitudin arcu.
Praesent hendrerit massa velit, vel pretium erat viverra quis. Proin non enim facilisis, venenatis dolor ut, dapibus nulla. Morbi vestibulum mollis felis ut venenatis. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus
mus. Ut mollis velit nulla, et tristique sapien auctor eu. Phasellus tincidunt mauris elit, vel fringilla leo consectetur a. Vivamus a porta magna. Mauris hendrerit leo eget sapien aliquet dignissim. Nunc id sem est. Integer sed lacus est. Nulla sit
amet sapien et ex aliquam malesuada quis vel eros. Interdum et malesuada fames ac ante ipsum primis in faucibus. Phasellus turpis ligula, elementum sit amet sapien nec, malesuada fringilla nibh. Duis euismod, purus semper viverra aliquam, ligula sem
vehicula mi, sit amet cursus mauris augue vel enim. Donec lacinia diam quis sapien laoreet vulputate in eu est. Proin consequat, ex vitae molestie pellentesque, libero purus pellentesque arcu, id porttitor orci sem a lectus. Morbi mattis in metus quis
euismod. Nam arcu augue, imperdiet eu felis eu, rhoncus facilisis lectus. Nullam placerat, tortor non tincidunt tristique, purus magna cursus leo, vitae sagittis odio turpis sodales nisi. Nullam vehicula erat nisl, ac venenatis massa rutrum sed. Mauris
massa tortor, volutpat vel nisl a, consectetur molestie sapien. Quisque eu elit nulla. Praesent at eros vehicula, lobortis purus quis, efficitur velit. Donec eget faucibus nisl. Praesent pharetra mattis porta. Donec volutpat lacinia dui non maximus.
Vivamus eu sodales leo. Ut eu ipsum scelerisque, consectetur turpis condimentum, malesuada elit. Proin tincidunt mauris metus, eu tincidunt ex ultrices ut. Sed sollicitudin leo nunc, in pharetra ligula egestas ut. Etiam suscipit eget ligula ut convallis.
Ut tempus tellus id ultrices rutrum. Nam accumsan fermentum metus, tristique gravida eros ultricies eget. Integer tortor diam, posuere ut ornare quis, bibendum ut tellus. Maecenas imperdiet lacus vitae felis viverra, nec dignissim lacus volutpat. Curabitur
et elit vehicula ipsum luctus tempor et sed enim. Fusce ultrices eget ante nec consectetur. Donec commodo nunc eget diam tristique, at euismod nisl commodo. Fusce felis neque, vulputate ut tincidunt sed, commodo in risus. Quisque sed magna sodales tortor
condimentum aliquam. Phasellus mattis justo eget diam tincidunt luctus. Cras pharetra ultrices sem, sed sollicitudin purus feugiat sed. Vivamus vitae tempor velit.
<!-- end original document -->
<div class='overlay'>
<!-- this div is my overlay. It should size to the content of the document body, not the viewport. Careful setting the body's position to relative, the other div will change!-->
</div>
</body>
I think you're best off appending one element to the body (unless you have access to some higher stacked element available to extensions) and simply use the element.getClientBoundingRect() to obtain the position and dimensions.
function applyStyle(element, styles) {
for (var key in styles) {
element.style[key] = styles[key];
}
}
var overlay = document.body.appendChild(document.createElement('div')),
indicator = overlay.appendChild(document.createElement('div'));
// apply the styles
applyStyle(overlay, {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
zIndex: 2147483647, // it doesn't get higher than this
pointerEvents: 'none'
});
applyStyle(indicator, {
position: 'absolute',
border: '1px dotted red',
backgroundColor: 'rgba(255,0,0,0.2)'
});
window.addEventListener('mouseover', function(event) {
var bound = event.target.getBoundingClientRect();
applyStyle(indicator, {
top: bound.top + 'px',
left: bound.left + 'px',
width: bound.width + 'px',
height: bound.height + 'px'
});
});
.foo {
position: absolute;
top: 30px;
left: 10px;
width: 300px;
border: 1px solid gold;
}
.bar {
position: relative;
width: 40%;
margin: 200px auto 0;
max-height: 10em;
overflow: hidden;
border: 1px solid green;
}
<div class=foo>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ut nibh dapibus tellus varius tristique vitae id elit. Fusce vestibulum neque a scelerisque pellentesque. Vestibulum eu odio risus. Aliquam id tellus in mauris sollicitudin vestibulum. Aenean vestibulum et massa vel dapibus. Pellentesque eu lectus odio. Aliquam vitae fermentum mauris. Pellentesque feugiat sem vel dolor imperdiet tempor.
</div>
<div class=bar>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ut nibh dapibus tellus varius tristique vitae id elit. Fusce vestibulum neque a scelerisque pellentesque. Vestibulum eu odio risus. Aliquam id tellus in mauris sollicitudin vestibulum. Aenean vestibulum et massa vel dapibus. Pellentesque eu lectus odio. Aliquam vitae fermentum mauris. Pellentesque feugiat sem vel dolor imperdiet tempor.
</div>
The bits of "trickery" in here involve:
using the maximum z-index combined with the overlay element being the last element within <body> makes it nearly impossible for any page to rise above it
the little known getBoundingClientRect treasure
pointer-events: none css, removing the interactivity from the overlay element (simply add pointer-events: auto on the indicator to re-enable)
As you are targeting one specific browser and a (evergreen) modern one, I don't think you should use jQuery. You don't need it.
I don't know whether jQuery is an option but I couldn't resist... Here's how you could use jQuery to style your overlay
var $thingToOverlay = $('#someDivOrWhatever'); // use $(document) for whole page
var $overlay = $('.overlay');
var getMaxZ = function($elements){
var z;
return Math.max.apply(null, $elements.map(function(){
return isNaN(z = parseInt($(this).css("z-index"), 10)) ? 0 : z;
}));
};
$overlay.css({
'position': 'absolute',
'box-sizing': 'border-box',
'background-color': 'red',
'height': $thingToOverlay.height(),
'width': $thingToOverlay.width(),
'top': $thingToOverlay.offset().top, // don't use this for whole page (document), just set to 0
'left': $thingToOverlay.offset().left, // ditto
'z-index': getMaxZ($overlay.siblings()) // assuming overlay is last on page, no need to +1
});
This will obviously need some logic around it depending on whether the overlay needs to cover the whole page or just a div but you get the idea?
I am using jQuery to detect which div is bigger out of two columns. The smaller div gets a class of .js-small-content. That class has a position:fixed on it.
However the issue that I am having is that I need to be able to scroll the fixed content. Which I understand sounds weird as why would I want to scroll something thats fixed?
If you take a look at my jsFiddle you will see that I need to be able to scroll the cat content so I can see all the images.
This is an example of the effect that I am after. You can see that the small content allows you to scroll it first and then once it has all been viewed it then fixes to the bottom of the content and continues scrolling the images on the left.
I think I may need to do something with the viewport on scroll but I'm not sure how to achieve this?
Here is my code:
var a = document.querySelector('#single__images');
var b = document.querySelector('#single__content');
var aH = a.scrollHeight;
var bH = b.scrollHeight;
(aH > bH ? b.classList.add("js-small-content") : a.classList.add("js-small-content"));
HTML:
<article>
<div id="single__image"><img src="#"/></div>
<div id="single__content">Text goes here</div>
</article>
I have worked really long for this, as was challenging for me. Finally made it.
According to you, you want to add class and remove class to smaller one among two div's. Which i have accomplished(but its' not right way to do at all) with my own other way.
I have made the smaller div to stop scroll when reaches at three fourth of window position from top.
JSFiddle : Demo
$(window).scroll(function()
{
var divImg = document.getElementById("single__images").id;
var divCont = document.getElementById("single__content").id;
// Height of single__content
var hC = $("#" + divCont).outerHeight();
// Height of single__images
var hI = $("#" + divImg).outerHeight();
// Check out the smaller one
if(hC<hI)
{
var samllOne = document.getElementById("single__content").id;
}
else
{
var samllOne = document.getElementById("single__images").id;
}
// Height of Smaller Div
var h = $("#" + samllOne).outerHeight();
// Position of Smaller Div from top
var topPos = $("#" + samllOne).position();
var topPos = topPos.top;
// Height of Smaller Div
var h = $("#" + samllOne).outerHeight();
// Div Height + TOP Space from from Body
var bottomCont = topPos + h;
// Checks current Scroll
var curScroll = $(this).scrollTop();
var windowH = $(window).innerHeight();
var windowMid = windowH / 2;
var midOfMid = windowMid / 2;
var threeFourth = windowMid + midOfMid;
var bottomTouch = h - threeFourth;
if(curScroll >= bottomTouch)
{
$("#" + samllOne).css({position: "fixed", top: "-" + bottomTouch + "px" });
}
else
{
$("#" + samllOne).css({position: "relative", top: "0px" });
}
});
article {
position:relative;
}
#single__images {
float:left;
width:200px;
}
img {
max-width:100%;
width:100%;
}
#single__content {
float:right;
width:200px;
right:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<article>
<div id="single__images">
<div class="inner">
<img src="http://placekitten.com.s3.amazonaws.com/homepage-samples/408/287.jpg"/>
<img src="http://placekitten.com.s3.amazonaws.com/homepage-samples/408/287.jpg"/>
<img src="http://placekitten.com.s3.amazonaws.com/homepage-samples/408/287.jpg"/>
<img src="http://placekitten.com.s3.amazonaws.com/homepage-samples/408/287.jpg"/>
<img src="http://placekitten.com.s3.amazonaws.com/homepage-samples/408/287.jpg"/>
</div>
</div>
<div id="single__content">
<div class="inner">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin commodo sed libero non lobortis. Aliquam aliquam vulputate felis. Phasellus hendrerit tellus ut libero bibendum rhoncus. Cras et ultricies neque. Curabitur posuere leo scelerisque mattis semper. In et arcu dictum, dictum libero ac, blandit nibh. Ut pharetra velit non blandit pretium. Suspendisse malesuada sodales orci, nec interdum ligula vestibulum ut. Mauris libero massa, tempus vel eleifend sit amet, efficitur nec sem.
Vivamus pretium malesuada ligula quis pulvinar. Duis ornare at massa et elementum. In ac consectetur turpis. Duis in velit nec nunc feugiat semper at in augue. Praesent ut odio quam. Ut faucibus eget massa a suscipit. Mauris fermentum est sed hendrerit lacinia. Mauris ac eleifend dolor. Phasellus rutrum volutpat efficitur. Maecenas vestibulum auctor massa, non dapibus diam laoreet id. Curabitur tincidunt massa vitae nibh varius iaculis. Duis sit amet nisi tempor, vestibulum ipsum at, rutrum purus. Mauris accumsan vulputate convallis. Morbi hendrerit ultrices erat, eu mollis neque faucibus id. Fusce sed magna semper justo placerat placerat quis eget augue.
Phasellus fermentum laoreet felis nec efficitur. Donec ultrices rutrum auctor. Duis faucibus rutrum tortor, ut eleifend libero pellentesque vitae. In nec ullamcorper justo. Donec eget aliquam est. Phasellus semper aliquam odio eu interdum. Praesent ultricies lectus nibh, ac bibendum lacus tempor sed. In ac ultrices sapien, vitae iaculis diam. Nullam pharetra lacus quis facilisis finibus. In a nisl aliquam, viverra dolor quis, auctor metus. Cras nec euismod nulla.
Duis sed ultrices erat. Sed semper lorem vel turpis aliquam vulputate. Nam ornare mauris a lorem posuere, id ultrices erat fringilla. Morbi eget posuere felis. Donec semper odio vitae porta bibendum. Duis sit amet metus at ligula iaculis pretium. Quisque at consectetur tortor. Etiam nec nisi porttitor, dignissim odio quis, condimentum risus. Quisque ipsum ipsum, pulvinar vel mi non, semper fringilla lacus. Mauris vestibulum mauris semper mauris venenatis, vitae suscipit dolor tincidunt. Aliquam eget mi lacus.
Nullam hendrerit sem ligula, sit amet malesuada ipsum rhoncus ut. Aenean urna nisl, finibus at arcu a, posuere aliquet odio. Fusce mollis dapibus leo, non aliquam tellus facilisis sit amet. Nunc commodo mauris eu gravida vehicula. Vestibulum sagittis magna orci, in tempus urna lacinia ut. Suspendisse potenti. Pellentesque ultrices, tellus sed laoreet tincidunt, urna mi facilisis sapien, a pretium lacus leo vitae elit.
</div>
</div>
</article>
I updated your JSFiddle project.
I just added the following to your CSS file. Hope this helps and is kind of self explaining.
.js-small-content {
position:absolute;
overflow-y:scroll;
overflow-x:hidden;
height:130px;
}
I have a fixed header function like below. I would like to change dynamically "100" value while window resizing.
I was trying to wrap everything in sth like "if (screen.width >= 1200)" or "jQuery(window).on('resize', function ()" but this kind of stuff is working only with page refresh.
jQuery(document).ready(function($) {
var $window = $(window),
$stickyEl = $('.tabsmenu > ul'),
elTop = $stickyEl.offset().top - 100;
$window.scroll(function() {
if ($window.scrollTop() < 900) {
$stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);
} else {
$stickyEl.removeClass('sticky');
}
});
});
Any tips?
This may not be perfect but it's what I think what you want to do and the way I would do it. This just gets the scroll value and then does some math to calculate how much it needs to change. I have added a bunch of content to let it scroll.
window.onload = function() {
$("#everything").scroll(function() {
var startAt = 40; //How many pixles scrolled to start effect, 0 would match link
if ($("#everything").scrollTop() >= startAt) {
var scroll = $("#everything").scrollTop(),
total = 0, // go to this value
distance = 40, //distance to shrink
value = (scroll < distance) ? total : total + (distance - (scroll - startAt));
$("#head").css("height", value); //change #head to what ever you want to shrink
} else {
$("#head").css("background-color", value);
}
});
}
html,
body {
overflow: hidden;
/* Disables regular scrolling */
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
#everything {
overflow: scroll;
/* enables content to scroll */
position: relative;
width: 100%;
height: 100%;
padding-top: 40px;
}
#head {
width: 100%;
height: 40px;
background-color: red;
position: fixed;
top: 0px;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<div id="everything">
<div id="head">header</div>
<span>
Text Following text is so the page can scroll: <br/>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer porta velit eu turpis imperdiet congue. Morbi nec mi ipsum. Nam eu nunc in lorem sagittis feugiat a quis nisl. Donec suscipit leo quis magna egestas, id convallis leo gravida. Curabitur finibus lectus ut metus feugiat, eu tincidunt eros tempor. Fusce facilisis nunc vulputate, posuere velit nec, ultrices diam. Vestibulum aliquam velit in lectus imperdiet, vitae condimentum lectus finibus. Aliquam ac arcu eget velit molestie rhoncus. Etiam rhoncus, tellus nec lacinia porta, diam lorem ultrices sem, et dignissim ipsum augue non augue. Suspendisse tincidunt felis sit amet orci accumsan, at ornare tellus viverra. Nam viverra nulla in urna elementum ornare.Sed interdum nisi libero, id porta turpis consectetur vitae. Curabitur nunc ex, interdum eget hendrerit maximus, faucibus non est. Etiam scelerisque condimentum eleifend. Integer ac ligula eget magna porta tristique at eu neque. Sed venenatis ipsum non metus sodales finibus. Suspendisse nec nunc lobortis ligula venenatis tristique. Suspendisse aliquam leo elit, et pretium ipsum tempor sed. Maecenas tincidunt dictum leo sit amet accumsan. Nullam eu viverra nulla. Aenean vehicula tellus a mauris malesuada interdum. Sed libero lacus, consectetur at condimentum vel, egestas vitae nisl.Mauris facilisis tincidunt magna, at gravida elit. Cras molestie eros sed tincidunt ultricies. Pellentesque eleifend egestas orci, sit amet condimentum nisl semper eleifend. Sed ipsum elit, aliquet nec lacinia a, maximus eu dolor. Quisque finibus efficitur odio gravida convallis. Vivamus nec velit in est ornare luctus at a risus. In hac habitasse platea dictumst. Proin condimentum eget est non posuere. Vivamus ante quam, bibendum in tincidunt ut, egestas sed mauris. Nunc non interdum nibh, nec ornare tellus. In interdum elit nisi, a interdum est tempor id. Cras a elit ut purus ornare mollis sit amet ut est. Cras ut ex sed neque lacinia accumsan quis aliquet turpis. Quisque nisl nunc, pretium sed lectus pretium, lacinia ornare magna. Curabitur sit amet felis turpis. Morbi nisi mi, mattis quis tempor ut, accumsan nec ex.
</span>
</div>
</body>
</html>