Reverse scroll element using jQuery - javascript

HAVE FOUND THE SOLUTION FOR BELOW PROBLEM : here is the Js Fiddle
special thanks to jonhkr
I have been working on reverse scroll in jquery and i need help with it. My stuff/code : Js Fiddle
Achieved:
when the content is scrolled down the rocket moves up.
Problem:
When the rocket is dragged up the content has to scroll down.
adding "containment" to the drag-able doesn't seem to work.
this has to work with overflow as hidden.
For those without Fiddle:
HTML:
<div id="test">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas eget nisi ipsum. Donec semper, justo at fringilla condimentum, felis tellus ultricies dolor, id convallis metus nulla quis est. Vivamus facilisis orci vel lectus blandit commodo blandit sem tempor. Curabitur condimentum, diam quis pretium feugiat, sem ante pretium tortor, in lobortis massa eros vitae dui. Nullam nisi mauris, condimentum a feugiat in, euismod quis augue. Maecenas euismod adipiscing tellus. Aliquam elementum egestas dolor, vel aliquam nulla tincidunt eget. Etiam risus elit, scelerisque eu volutpat sed, faucibus non ante. Donec sed nunc erat, eget facilisis risus. Etiam id odio tortor. Sed aliquam viverra volutpat. Sed gravida lectus eu mi ornare in feugiat magna elementum. Pellentesque in dolor ligula.
Maecenas condimentum nisl eget arcu elementum nec imperdiet risus lobortis. Suspendisse id placerat turpis. Etiam dolor quam, placerat et volutpat nec, ultricies sed lorem. Fusce volutpat lobortis est ut pellentesque. Donec enim mauris, pretium quis gravida vitae, pellentesque ac nibh. Proin condimentum aliquam scelerisque. Vestibulum aliquet pharetra dapibus. Donec id nisi non nibh fringilla auctor et eget erat. Morbi pretium mauris sed orci pretium aliquam. Nulla pharetra venenatis nunc, in venenatis purus tempor vitae. Vivamus tincidunt dui non eros gravida sit amet consectetur nibh lacinia.
Maecenas semper ligula et urna tincidunt placerat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse arcu urna, facilisis at tempus id, posuere sed lacus. Vestibulum in feugiat tellus. Nullam suscipit, velit nec tincidunt pellentesque, enim odio ornare mauris, quis faucibus sem sapien sed turpis. Nulla sit amet risus in magna iaculis scelerisque sit amet vel erat. Morbi eu vestibulum nulla. Etiam auctor auctor felis, nec sodales velit condimentum non. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Duis eu massa diam, eu porttitor eros. Etiam blandit, turpis ac volutpat gravida, massa lorem congue orci, eget fringilla eros felis quis elit. Suspendisse quam tellus, pretium non mattis ut, laoreet in diam. Suspendisse ante odio, venenatis vel condimentum vitae, varius id sapien. Quisque ac nunc ipsum. Mauris porttitor blandit magna, id rutrum ipsum pellentesque non. In suscipit diam ligula, non tristique diam.
Aliquam interdum ante at nisl sagittis vel luctus eros fringilla. Vestibulum purus orci, ultrices at tristique et, malesuada eget enim. Praesent commodo erat vel massa auctor id elementum elit elementum. Duis diam urna, mollis ut imperdiet aliquam, commodo id dui. Etiam vulputate facilisis dui id convall
</div>
<div id="track">
<div id="rocket">
</div>
</div>
<div id="xpos" style="clear:both">
</div>
CSS:
#track {
height: 400px;
width: 48px;
overflow: hidden;
margin: 10px 0 0 10px;
background:#ccc;
float:left;
}
#rocket{
height:48px;
width:48px;
background:#ccc url('http://www.veryicon.com/icon/preview/System/GANT%203/Rocket,%20This%20is%20a%20damn%20good%20Icon.jpg');
}
​
JS (JQuery 1.8.2 & Jquery UI):
$(document).ready(function() {
$(function() {
var left = parseInt($('#track').css('margin-left'), 10);
var top = parseInt($('#track').css('margin-top'), 10);
$("#rocket").draggable({
containment: "#track",
axis: "y",
scroll: false,
drag: function(event, ui) {
// Show the current dragged position of image
var currentPos = $(this).position();
$("div#xpos").text("CURRENT: \nLeft: " + (currentPos.left - left) + "\nTop: " + (currentPos.top - top));
}
});
});
});​

I changed a bit your code to solve these problems:
Adding "containment" to the drag-able doesn't seem to work.
var draggingRocket = false;
$("#test").scroll(function(event) {
if(!draggingRocket){
var st = $(this).scrollTop();
var pos = iHeight - (st / cr);
$("#rocket").css("top", pos);
}
});
//rocket drag
$("#rocket").draggable({
containment: $('#track'),
axis: "y",
scroll: false,
start: function(event, ui) {
draggingRocket = true;
},
drag: function(event, ui) {
// Show the current dragged position of image
var currentPos = $(this).position();
$("div#xpos").text("CURRENT: \nLeft: " + (currentPos.left - left) + "\nTop: " + (currentPos.top - top));
$("#test").scrollTop(currentPos.top);
},
stop: function(event, ui) {
draggingRocket = false;
}
});

First of all, good work.
Well I don't think your solution is far-fetched. Basically you need to use
$("#test").scrollTop((top - currentPos.top)*cr);
to set the scrollTop of the div test. The equation I have used it not accurate, but you can change it accordingly.
Hope this gives you lead:
Demo: http://jsfiddle.net/CZvWC/7/

Related

jQuery to Javascript/Vue

I want to create a custom search box that can jump to its matches using mark.js mark.js web page.
They do have an example here:
https://jsfiddle.net/julmot/973gdh8g/
But it is written using jQuery.
I tried converting it to JS/Vue (using Quasar), but now I couldn't get it to work.
No errors, but also no highlights.
I have updated jQuery lines like:
$prevBtn = $("button[data-search='prev']")
to:
prevBtn = document.querySelector('#prev')
And these, I dont know how to convert the others, such as:
$nextBtn.add($prevBtn).on("click", function() {})
Here is my fiddle (simplified version, but not completely done yet, also make sure to click "Search" after input):
https://codepen.io/keechan/pen/JjWEYmP?editors=1111
What am I missing? Help please!
I rewrote their jQuery example using pure JavaScript.
You should be able to compare the two examples to see how the various jQuery functions translate to JavaScript and then implement them into your Vue project.
https://jsfiddle.net/75qyu3j8/
I tried to keep the variable names the same so it is easier to understand.
document.body.onload = function() {
// the input field
var $input = document.querySelector("input[type='search']"),
// clear button
$clearBtn = document.querySelector("button[data-search='clear']"),
// prev button
$prevBtn = document.querySelector("button[data-search='prev']"),
// next button
$nextBtn = document.querySelector("button[data-search='next']"),
// the context where to search
$content = document.querySelector(".content"),
$contentMark = new Mark($content),
// jQuery object to save <mark> elements
$results,
// the class that will be appended to the current
// focused element
currentClass = "current",
// top offset for the jump (the search bar)
offsetTop = 50,
// the current index of the focused element
currentIndex = 0;
/**
* Jumps to the element matching the currentIndex
*/
function jumpTo() {
if ($results.length) {
var position,
$current = $results[currentIndex];
$results.forEach($result => $result.classList.remove(currentClass));
if ($current) {
$current.classList.add(currentClass);
position = $current.offsetTop - offsetTop;
window.scrollTo(0, position);
}
}
}
/**
* Searches for the entered keyword in the
* specified context on input
*/
$input.addEventListener("input", function() {
var searchVal = this.value;
$contentMark.unmark({
done: function() {
$contentMark.mark(searchVal, {
separateWordSearch: true,
done: function() {
$results = $content.querySelectorAll("mark");
currentIndex = 0;
jumpTo();
}
});
}
});
});
/**
* Clears the search
*/
$clearBtn.addEventListener("click", function() {
$contentMark.unmark();
$input.value = ""
$input.focus();
});
/**
* Next and previous search jump to
*/
$nextBtn.after($prevBtn);
function prevNextHandler() {
if ($results.length) {
currentIndex += (this.dataset.search === "prev" ? -1 : 1);
if (currentIndex < 0) {
currentIndex = $results.length - 1;
}
if (currentIndex > $results.length - 1) {
currentIndex = 0;
}
jumpTo();
}
}
$nextBtn.addEventListener("click", prevNextHandler);
$prevBtn.addEventListener("click", prevNextHandler);
};
mark {
background: yellow;
}
mark.current {
background: orange;
}
.header {
padding: 10px;
width: 100%;
background: #eee;
position: fixed;
top: 0;
left: 0;
}
.content {
margin-top: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/mark.min.js"></script>
<div class="header">
Search:
<input type="search" placeholder="Lorem">
<button data-search="next">↓</button>
<button data-search="prev">↑</button>
<button data-search="clear">✖</button>
</div>
<div class="content">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eu ullamcorper orci, eget porttitor justo. Aliquam id sollicitudin elit. Nulla in sodales ipsum. Donec vulputate venenatis magna. Vestibulum sit amet leo lacinia, cursus lectus in, gravida
metus. In ultricies sed tortor non pellentesque. Mauris quis tempor neque. Donec nec sagittis magna. Integer fringilla posuere metus eu mollis. Ut ac porta metus. Duis sed lacinia metus. Nunc malesuada iaculis risus vitae bibendum.
</p>
<p>
Vivamus posuere condimentum leo eu hendrerit. Pellentesque placerat iaculis ante a rhoncus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum eu ipsum ac magna congue congue sed maximus tortor. Vivamus id odio elementum, vehicula nunc
ut, efficitur felis. Nullam hendrerit velit libero, gravida porttitor tortor ullamcorper eu. Ut ut lectus non enim sagittis aliquam quis in orci. Donec a arcu eu eros cursus cursus. Donec dictum dignissim tellus, dictum egestas purus pellentesque
sed.
</p>
<p>
Vestibulum eu ornare urna, nec aliquam lectus. Phasellus eu odio sapien. Vestibulum eu turpis at lorem sagittis posuere. Quisque tellus nunc, facilisis id lacus nec, ornare rhoncus elit. Vivamus vehicula eros a condimentum venenatis. Sed orci massa, pulvinar
sed erat nec, pellentesque suscipit leo. Mauris lobortis tincidunt nunc, sed tempus ex congue vitae. Curabitur lobortis mauris in ex malesuada, quis vehicula neque lobortis. Curabitur aliquam porttitor tellus eget tempus. Donec maximus tempus tristique.
Aliquam tincidunt odio dictum, scelerisque ipsum ut, facilisis quam. Ut nec malesuada neque.
</p>
<p>
Proin felis eros, tincidunt vitae scelerisque sit amet, dictum nec ante. Praesent tincidunt ac lacus nec elementum. Vivamus sed gravida purus, sed efficitur tortor. Nulla non molestie arcu. Sed tincidunt consectetur ligula sed lobortis. In non sapien
ac urna lacinia placerat sed nec lacus. Aenean lobortis tincidunt sapien a hendrerit. Quisque eu turpis accumsan nisl blandit efficitur.
</p>
<p>
Nam sit amet pellentesque est. Sed ligula turpis, ultricies sit amet mattis elementum, tristique non risus. Phasellus at congue ex. Proin nisi leo, vestibulum vitae accumsan in, imperdiet id dolor. Quisque at blandit nisl. Class aptent taciti sociosqu
ad litora torquent per conubia nostra, per inceptos himenaeos. Nunc eget metus augue. Morbi faucibus venenatis sapien, fermentum porttitor felis pharetra a. Nam interdum nibh tortor, quis maximus turpis blandit eget. Praesent in feugiat neque, sed
vulputate quam. Curabitur erat quam, efficitur et congue quis, iaculis euismod libero. Quisque odio sapien, efficitur non mauris ac, tincidunt condimentum turpis.
</p>
<p>
Maecenas dapibus aliquam vehicula. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Praesent convallis viverra leo quis porta. Sed sit amet porttitor quam. Fusce nec risus non augue consectetur ultricies. Aliquam
elit lorem, tincidunt ac dolor vel, vulputate consectetur ex. In hac habitasse platea dictumst. Sed eget nisl aliquam, cursus odio nec, commodo lorem. Nulla mollis tortor eu odio rutrum vulputate. Donec condimentum molestie mauris, nec sodales nisi
volutpat aliquam. Nulla mollis libero sed nibh volutpat, ac mollis elit tincidunt. Vestibulum cursus velit vitae felis aliquam ultricies. Donec vehicula dictum feugiat. Vestibulum volutpat sollicitudin sagittis.
</p>
<p>
Aliquam consequat, diam eu ullamcorper porta, diam eros rhoncus turpis, in rutrum sem diam a risus. Duis lacinia velit sed ante feugiat venenatis. Aenean orci leo, dictum non finibus nec, dignissim quis eros. Nullam sit amet orci ac purus blandit commodo
sit amet eget neque. Sed pellentesque dictum tortor. Ut dui erat, tempus in odio in, aliquet convallis mi. Morbi efficitur justo ante, quis ultricies turpis suscipit ac. Sed sit amet nisl rutrum, laoreet mauris id, ullamcorper orci. In facilisis nisi
eget fringilla imperdiet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi ut ultricies dui. Pellentesque elit urna, imperdiet sed congue eget, hendrerit sed urna.
</p>
<p>
Proin vel hendrerit nulla. Vivamus vehicula nibh nec lorem blandit, quis aliquam ipsum suscipit. Nulla at vestibulum felis. Aenean ac nibh eget enim molestie pulvinar. Duis nulla justo, tristique id nulla nec, faucibus imperdiet arcu. In vel pretium dui,
at lobortis sapien. Phasellus ullamcorper id enim eget dictum. Ut imperdiet rutrum est a rutrum. Curabitur eget dignissim tellus. Fusce tempus leo nisl, vitae auctor diam feugiat sit amet. Vestibulum accumsan justo eget odio imperdiet, consectetur
efficitur ex dapibus.
</p>
<p>
Sed pharetra odio a nibh pharetra rutrum. Suspendisse ut ullamcorper lectus. Donec ipsum mauris, congue et lobortis sit amet, ultricies ac tellus. Sed nisi risus, condimentum at varius quis, condimentum ac velit. In condimentum, magna sed ornare eleifend,
dolor nulla mollis felis, quis feugiat elit turpis non ipsum. Etiam aliquam est imperdiet dolor rutrum, at varius leo sodales. Morbi quis iaculis metus.
</p>
<p>
Maecenas auctor nec ligula ac luctus. Nam sit amet euismod mauris. Donec et diam sit amet eros efficitur tempor. Mauris non erat sit amet nunc interdum pulvinar. Sed luctus hendrerit justo eget pulvinar. Cras non arcu sed ligula faucibus pulvinar. Sed
egestas risus nisl. Duis quis arcu tempus, cursus erat ac, gravida enim. Cras et condimentum ante. Nullam eleifend egestas velit, quis semper est imperdiet non. Donec quis purus varius, placerat mi et, dictum lorem. Sed quis finibus nisi, vitae molestie
metus. Donec lobortis eros quis vestibulum vulputate.
</p>
</div>

Why is scroll-behavior:smooth not working but javascript window.scroll smooth is?

I have a navigation bar to scroll down to anchor elements. The navbar is inside the body.
My css :
body {
scroll-behavior: smooth;
}
In the page, I also use some javascript. One is a javascript with the following function to navigate to other page elements :
window.scroll({
top : pos,
left : 0,
behavior : 'smooth'
});
With Chrome, when I call the javascript function, the scroll is smooth. But when I navigate to anchors through navigation bar links, it is not smooth.
Would someone care to explain me why ?
Also with Firefox both scroll from navigation bar & javascript function are smooth. I think it's a bit wierd that one work but not the other.
EDIT : my workaround is as follow (vanilla JS / works with all modern browsers) :
let pos = document.querySelector(element).offsetTop;
if ('scrollBehavior' in document.documentElement.style) { //Checks if browser supports scroll function
window.scroll({
top : pos,
left : 0,
behavior : 'smooth'
});
} else {
smoothScrollTo(0, pos, 500); //polyfill below
}
And the fallback scroll function :
window.smoothScrollTo = function(endX, endY, duration) {
let startX = window.scrollX || window.pageXOffset,
startY = window.scrollY || window.pageYOffset,
distanceX = endX - startX,
distanceY = endY - startY,
startTime = new Date().getTime();
// Easing function
let easeInOutQuart = function(time, from, distance, duration) {
if ((time /= duration / 2) < 1) return distance / 2 * time * time * time * time + from;
return -distance / 2 * ((time -= 2) * time * time * time - 2) + from;
};
let timer = window.setInterval(function() {
let time = new Date().getTime() - startTime,
newX = easeInOutQuart(time, startX, distanceX, duration),
newY = easeInOutQuart(time, startY, distanceY, duration);
if (time >= duration) {
window.clearInterval(timer);
}
window.scrollTo(newX, newY);
}, 1000 / 60); // 60 fps
};
Based on documentation, scroll-behavior: smooth not working on body element (try it):
The scroll-behavior property of the HTML body element is not
propagated to the viewport.
But it works on other selectors like html (try here).
Also you can try pure JavaScript solution (example):
function scrollToTop() {
window.scrollTo({
top: 1000,
behavior: 'smooth'
});
}
This worked for me:
* {
scroll-behavior: smooth;
}
It's been some time, but some people have their JavaScript disabled on browsers, so I don't think that would be the best option. The problem with adding: body {scroll-behavior: smooth;} is that it won't work unless you add it to the html. For example:
On body:
body {
scroll-behavior: smooth;
}
a {
background-color: lightgray;
padding: 10px 20px;
color: black;
right: 10px;
margin-bottom: 10px;
}
<!DOCTYPE HTML>
<html>
<head>
<title>No Scroll Effect On Body</title>
</head>
<body>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas gravida varius turpis, ac dignissim purus molestie quis. Aliquam erat volutpat. Aenean ipsum neque, faucibus ut imperdiet nec, aliquam eget purus. Phasellus ultricies porttitor neque, a porttitor tortor pulvinar non. Phasellus in orci porttitor nulla mattis cursus nec ut ex. Vivamus non elit at dolor imperdiet bibendum. Ut leo dolor, aliquet ut magna eu, hendrerit consequat quam. Pellentesque eget odio felis. Integer id posuere mi. Ut quis velit pulvinar, auctor sem nec, consectetur diam. Fusce sed ex eu sem bibendum aliquam ultrices ut ipsum. In hac habitasse platea dictumst. Aenean imperdiet ex eu velit malesuada volutpat. Sed molestie imperdiet condimentum. In suscipit, nulla nec viverra tristique, dui tellus tristique mi, eget laoreet tortor nunc vel nunc. Nam tristique rutrum vulputate.
Donec imperdiet nisl non ligula ultricies condimentum. Suspendisse nisi est, lobortis vitae enim at, porta mollis erat. Sed in orci nunc. Aliquam non dui et urna volutpat dignissim varius sed nulla. Duis fringilla vestibulum ipsum, a fringilla sapien bibendum vel. Pellentesque non viverra magna, sed laoreet orci. Donec elit eros, imperdiet sit amet risus sed, placerat fermentum sem. In porta felis vulputate, suscipit nisi maximus, fringilla tellus. Vivamus nec dui accumsan, suscipit eros nec, sodales sapien. Mauris et viverra lectus. Curabitur massa quam, lacinia aliquam ante eget, auctor sollicitudin turpis. Phasellus imperdiet eros ornare arcu pulvinar, id cursus arcu volutpat. Nam sit amet magna eu magna suscipit posuere id quis nisi.
Quisque a diam sed magna luctus dignissim sit amet et elit. Vivamus fringilla posuere sapien eu posuere. Proin bibendum libero ac eros maximus vehicula. Sed et diam eu lorem gravida pharetra at sed mauris. Cras dictum urna fringilla quam luctus elementum. Maecenas tincidunt arcu dolor, eget venenatis ex ornare eu. Vestibulum tempor tempus finibus. Mauris posuere, enim eu ornare molestie, quam urna iaculis massa, eu lacinia eros odio ac quam. Sed sem nunc, sollicitudin in imperdiet eu, molestie vel libero. Morbi in dui ut enim pharetra dictum egestas tempus velit. Morbi accumsan justo nec faucibus pulvinar. Ut pellentesque auctor purus. Maecenas id sagittis enim, tempor tristique quam.
Proin condimentum posuere scelerisque. Maecenas egestas vehicula vestibulum. Vestibulum pharetra nunc nec orci scelerisque, fermentum pellentesque quam pretium. Nam odio tortor, aliquet nec sem quis, rutrum ornare lectus. Fusce scelerisque ullamcorper lacus vitae hendrerit. Donec tincidunt quis dolor ut sollicitudin. Vestibulum feugiat diam at odio fringilla, id ullamcorper diam scelerisque. Aenean tempor tincidunt turpis id porttitor. Mauris gravida eleifend lorem, pellentesque cursus odio volutpat et. Mauris est nunc, bibendum congue purus vitae, luctus elementum est. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
<br />
<br />
<br />
Go to top
</body>
</html>
As you can see, it is not possible to work if it set on the body. But it will work if it set on the html:
html {
scroll-behavior: smooth;
}
a {
background-color: lightgray;
padding: 10px 20px;
color: black;
right: 10px;
margin-bottom: 10px;
}
<!DOCTYPE HTML>
<html>
<head>
<title>No Scroll Effect On Body</title>
</head>
<body>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas gravida varius turpis, ac dignissim purus molestie quis. Aliquam erat volutpat. Aenean ipsum neque, faucibus ut imperdiet nec, aliquam eget purus. Phasellus ultricies porttitor neque, a
porttitor tortor pulvinar non. Phasellus in orci porttitor nulla mattis cursus nec ut ex. Vivamus non elit at dolor imperdiet bibendum. Ut leo dolor, aliquet ut magna eu, hendrerit consequat quam. Pellentesque eget odio felis. Integer id posuere mi.
Ut quis velit pulvinar, auctor sem nec, consectetur diam. Fusce sed ex eu sem bibendum aliquam ultrices ut ipsum. In hac habitasse platea dictumst. Aenean imperdiet ex eu velit malesuada volutpat. Sed molestie imperdiet condimentum. In suscipit, nulla
nec viverra tristique, dui tellus tristique mi, eget laoreet tortor nunc vel nunc. Nam tristique rutrum vulputate. Donec imperdiet nisl non ligula ultricies condimentum. Suspendisse nisi est, lobortis vitae enim at, porta mollis erat. Sed in orci nunc.
Aliquam non dui et urna volutpat dignissim varius sed nulla. Duis fringilla vestibulum ipsum, a fringilla sapien bibendum vel. Pellentesque non viverra magna, sed laoreet orci. Donec elit eros, imperdiet sit amet risus sed, placerat fermentum sem. In
porta felis vulputate, suscipit nisi maximus, fringilla tellus. Vivamus nec dui accumsan, suscipit eros nec, sodales sapien. Mauris et viverra lectus. Curabitur massa quam, lacinia aliquam ante eget, auctor sollicitudin turpis. Phasellus imperdiet eros
ornare arcu pulvinar, id cursus arcu volutpat. Nam sit amet magna eu magna suscipit posuere id quis nisi. Quisque a diam sed magna luctus dignissim sit amet et elit. Vivamus fringilla posuere sapien eu posuere. Proin bibendum libero ac eros maximus
vehicula. Sed et diam eu lorem gravida pharetra at sed mauris. Cras dictum urna fringilla quam luctus elementum. Maecenas tincidunt arcu dolor, eget venenatis ex ornare eu. Vestibulum tempor tempus finibus. Mauris posuere, enim eu ornare molestie, quam
urna iaculis massa, eu lacinia eros odio ac quam. Sed sem nunc, sollicitudin in imperdiet eu, molestie vel libero. Morbi in dui ut enim pharetra dictum egestas tempus velit. Morbi accumsan justo nec faucibus pulvinar. Ut pellentesque auctor purus. Maecenas
id sagittis enim, tempor tristique quam. Proin condimentum posuere scelerisque. Maecenas egestas vehicula vestibulum. Vestibulum pharetra nunc nec orci scelerisque, fermentum pellentesque quam pretium. Nam odio tortor, aliquet nec sem quis, rutrum ornare
lectus. Fusce scelerisque ullamcorper lacus vitae hendrerit. Donec tincidunt quis dolor ut sollicitudin. Vestibulum feugiat diam at odio fringilla, id ullamcorper diam scelerisque. Aenean tempor tincidunt turpis id porttitor. Mauris gravida eleifend
lorem, pellentesque cursus odio volutpat et. Mauris est nunc, bibendum congue purus vitae, luctus elementum est. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Maecenas gravida varius turpis, ac dignissim purus molestie quis. Aliquam erat volutpat. Aenean ipsum neque, faucibus ut imperdiet nec, aliquam eget purus. Phasellus ultricies porttitor neque, a porttitor tortor pulvinar non. Phasellus in orci
porttitor nulla mattis cursus nec ut ex. Vivamus non elit at dolor imperdiet bibendum. Ut leo dolor, aliquet ut magna eu, hendrerit consequat quam. Pellentesque eget odio felis. Integer id posuere mi. Ut quis velit pulvinar, auctor sem nec, consectetur
diam. Fusce sed ex eu sem bibendum aliquam ultrices ut ipsum. In hac habitasse platea dictumst. Aenean imperdiet ex eu velit malesuada volutpat. Sed molestie imperdiet condimentum. In suscipit, nulla nec viverra tristique, dui tellus tristique mi, eget
laoreet tortor nunc vel nunc. Nam tristique rutrum vulputate. Donec imperdiet nisl non ligula ultricies condimentum. Suspendisse nisi est, lobortis vitae enim at, porta mollis erat. Sed in orci nunc. Aliquam non dui et urna volutpat dignissim varius
sed nulla. Duis fringilla vestibulum ipsum, a fringilla sapien bibendum vel. Pellentesque non viverra magna, sed laoreet orci. Donec elit eros, imperdiet sit amet risus sed, placerat fermentum sem. In porta felis vulputate, suscipit nisi maximus, fringilla
tellus. Vivamus nec dui accumsan, suscipit eros nec, sodales sapien. Mauris et viverra lectus. Curabitur massa quam, lacinia aliquam ante eget, auctor sollicitudin turpis. Phasellus imperdiet eros ornare arcu pulvinar, id cursus arcu volutpat. Nam sit
amet magna eu magna suscipit posuere id quis nisi. Quisque a diam sed magna luctus dignissim sit amet et elit. Vivamus fringilla posuere sapien eu posuere. Proin bibendum libero ac eros maximus vehicula. Sed et diam eu lorem gravida pharetra at sed
mauris. Cras dictum urna fringilla quam luctus elementum. Maecenas tincidunt arcu dolor, eget venenatis ex ornare eu. Vestibulum tempor tempus finibus. Mauris posuere, enim eu ornare molestie, quam urna iaculis massa, eu lacinia eros odio ac quam. Sed
sem nunc, sollicitudin in imperdiet eu, molestie vel libero. Morbi in dui ut enim pharetra dictum egestas tempus velit. Morbi accumsan justo nec faucibus pulvinar. Ut pellentesque auctor purus. Maecenas id sagittis enim, tempor tristique quam. Proin
condimentum posuere scelerisque. Maecenas egestas vehicula vestibulum. Vestibulum pharetra nunc nec orci scelerisque, fermentum pellentesque quam pretium. Nam odio tortor, aliquet nec sem quis, rutrum ornare lectus. Fusce scelerisque ullamcorper lacus
vitae hendrerit. Donec tincidunt quis dolor ut sollicitudin. Vestibulum feugiat diam at odio fringilla, id ullamcorper diam scelerisque. Aenean tempor tincidunt turpis id porttitor. Mauris gravida eleifend lorem, pellentesque cursus odio volutpat et.
Mauris est nunc, bibendum congue purus vitae, luctus elementum est. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
<br />
<br />
<br />
Go to top </body>
</html>
The good thing about this is that it is a cross-browser solution, as it is very uncommon to find a browser that disabled CSS. I hope this helps.
Maybe you want to try to smooth scroll using jQuery. I think native scrolling might not always support the smooth scroll. You'd be much safer using jQuery.
$("html, body").animate({ scrollTop: 0 }, "slow");
If you are using other anchors, you need to make sure they prevent default jumping and scroll. I'd use jQuery also.
Ref: https://css-tricks.com/snippets/jquery/smooth-scrolling/
I don't know if you still need an answer to this, but I came across an article that fixed it for me with just css: https://www.fourkitchens.com/blog/article/fix-scrolling-performance-css-will-change-property/
enter code here
setInterval(myTimer, 1);
var isTimerEnable = false;
var scroll_position = 0;
var getSelected_position =0;
var getCurrent_position =0;
var scroll_speed = 5;
function Current_Position(){
getCurrent_position = window.pageYOffset;
}
function myTimer() {
if(isTimerEnable == true){
if(scroll_position < getSelected_position){
scroll_position +=scroll_speed;
getCurrent_position =scroll_position;
window.scroll(0,scroll_position);
if(scroll_position >= getSelected_position){
isTimerEnable = false;
}
}
else{
scroll_position -=scroll_speed;
getCurrent_position =scroll_position;
window.scroll(0,scroll_position);
if(scroll_position <= getSelected_position){
isTimerEnable = false;
}
}
}
}
//NOTE ASSIGN THE Y POSITION OF YOUR DIV
function topNav_btn(setPosition){
scroll_position = getCurrent_position;
getSelected_position = setPosition;
isTimerEnable =true;
}
<!DOCTYPE HTML>
<html>
<head>
<title>No Scroll Effect On Body</title>
</head>
<body>
<button style="position:fixed; left:200px;" onclick="topNav_btn(0);">Go to form 1 </button>
<button style="position:fixed; left:300px;" onclick="topNav_btn(450);">Go to form 2 </button>
<button style="position:fixed; left:400px;" onclick="topNav_btn(900);">Go to form 3 </button>
<div id="form1"> Form 1 </div>
<br> <br> <br><br> <br> <br><br><br> <br> <br> <br><br> <br> <br><br><br>
<br> <br> <br><br> <br> <br><br><br>
<div id="form2"> Form 2 </div>
<br> <br> <br><br> <br> <br><br><br> <br> <br> <br><br> <br> <br><br><br>
<br> <br> <br><br> <br> <br><br><br>
<div id="form2"> Form 3 </div>
<br> <br> <br><br> <br> <br><br><br> <br> <br> <br><br> <br> <br><br><br>
<br> <br> <br><br> <br> <br><br><br>
</body>
</html>

how to temporarily block scroll

I'm trying to reproduce the following effect: http://tympanus.net/Development/ArticleIntroEffects/ and i got this far: http://codepen.io/vlrprbttst/pen/LGMVyj
the only difference with the demo is the scroll managing. on my example, if you scroll too much, you'll find yourself scrolled too far in the page. and that's something i want to prevent. in the codrops example instead, it looks like the scrolling is temporarily blocked, and is renabled once the animation of the disappearing header is finished.
i tried this:
function intro() {
var wh = window.innerHeight;
$(".header").css("height", wh);
$(".subsection").css("padding-top", (wh / 3 * 2));
$(window).scroll(function() {
var scroll = $(window).scrollTop();
var header = $(".header");
var subsection = $(".subsection");
if (scroll >= 1) {
header.addClass("header--scrolled");
subsection.addClass("header--scrolled");
$("body").css("overflow","hidden");
header.one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend',
function(e) {
$("body").css("overflow","scroll");
});
} else {
$(".subsection").removeClass("header--scrolled");
$(".header").removeClass("header--scrolled");
}
});
};
intro();
so basically if you scroll +1 pixel, you get $("body").css("overflow","hidden");and once the transition is done, you go back to $("body").css("overflow","scroll");
but this is not working.
any idea on how I can do this?
For make that .header must be in position absolute.
I have add a variable topT for check if is top or not and a timer for no scrolling page.
Please try:
CodePen : http://codepen.io/anon/pen/XXOdwN
HTML
<div class="header">
<h1>hello visitor</h1>
</div>
<div class="subsection">
<div class="subsection--inner">
<h2>welcome</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. In porttitor ipsum eu lacus commodo pulvinar. Donec nec facilisis augue. Nulla in magna iaculis, sagittis dolor vitae, scelerisque risus. Cras fermentum rhoncus nunc, vel gravida sapien tempor at.
Aliquam rhoncus, metus ac egestas aliquam, augue augue vulputate dolor, id sodales lorem sem quis lectus. Etiam rhoncus neque ligula. Ut ornare nec diam non sodales. Vivamus venenatis congue tellus vitae elementum. Ut sed quam pretium, faucibus
nulla id, ultrices mi. Suspendisse eleifend posuere augue a vulputate. Praesent nec nisl nisl. Ut molestie convallis ligula, eget commodo nisi cursus sit amet. Maecenas mollis enim in odio fermentum, ac commodo nibh tincidunt. Aliquam molestie ex
in nunc ornare faucibus. Pellentesque vel massa condimentum, dictum purus id, congue velit. Cras nec eleifend ipsum, eget lobortis tellus. Pellentesque sed tellus id sem consectetur viverra eget vel magna. Ut pretium ex nec malesuada laoreet. Quisque
et malesuada eros, non dignissim diam. Integer in semper erat, sit amet hendrerit ipsum. Duis volutpat ac libero non aliquam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aenean varius laoreet purus
sit amet porta. Mauris congue, orci quis ultricies ornare, ligula tortor ornare urna, sed fringilla turpis nulla ac sem. Nam nisi odio, consectetur nec nunc in, luctus pretium tellus. Suspendisse in leo elementum, rhoncus risus ut, blandit metus.
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In viverra urna vel turpis hendrerit, sed tincidunt dui fringilla. Proin mattis nisl nec mauris consequat congue. Praesent gravida eget dolor nec fermentum. Proin
finibus, magna elementum convallis viverra, leo nisi convallis magna, a condimentum nisl sem nec mauris. Sed ultricies lorem eu lectus tristique, sed ornare lorem auctor. Proin tincidunt enim dapibus nunc scelerisque, at consequat quam lobortis.
Nunc ornare lectus sit amet leo pharetra, at faucibus magna sodales. Cras auctor lacus lorem, ac porta libero feugiat vitae. Mauris metus velit, aliquam sit amet nunc eu, efficitur fermentum dolor. Suspendisse sed sagittis turpis, nec faucibus massa.
Fusce sagittis massa est, at sagittis est fermentum et. Curabitur egestas arcu eu neque elementum, sit amet sodales nibh viverra. Donec nec placerat nunc. Mauris non orci dapibus, porttitor leo quis, eleifend ante. Vivamus sed risus neque. Pellentesque
eget laoreet ante. Maecenas sed vehicula purus. Nam at sapien quis tortor vulputate tempor. Cras dignissim, metus sodales facilisis bibendum, dui erat faucibus elit, vel varius nisl lectus sed ante. Pellentesque ut magna consectetur est tempus vestibulum.
Maecenas fermentum metus nec accumsan volutpat. Mauris in viverra magna. Sed ante erat, blandit id fringilla eget, rhoncus at odio. Curabitur in metus nulla. Aliquam erat volutpat. Cras hendrerit augue massa, ullamcorper eleifend sapien ornare vel.</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. In porttitor ipsum eu lacus commodo pulvinar. Donec nec facilisis augue. Nulla in magna iaculis, sagittis dolor vitae, scelerisque risus. Cras fermentum rhoncus nunc, vel gravida sapien tempor at.
Aliquam rhoncus, metus ac egestas aliquam, augue augue vulputate dolor, id sodales lorem sem quis lectus. Etiam rhoncus neque ligula. Ut ornare nec diam non sodales. Vivamus venenatis congue tellus vitae elementum. Ut sed quam pretium, faucibus
nulla id, ultrices mi. Suspendisse eleifend posuere augue a vulputate. Praesent nec nisl nisl. Ut molestie convallis ligula, eget commodo nisi cursus sit amet. Maecenas mollis enim in odio fermentum, ac commodo nibh tincidunt. Aliquam molestie ex
in nunc ornare faucibus. Pellentesque vel massa condimentum, dictum purus id, congue velit. Cras nec eleifend ipsum, eget lobortis tellus. Pellentesque sed tellus id sem consectetur viverra eget vel magna. Ut pretium ex nec malesuada laoreet. Quisque
et malesuada eros, non dignissim diam. Integer in semper erat, sit amet hendrerit ipsum. Duis volutpat ac libero non aliquam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aenean varius laoreet purus
sit amet porta. Mauris congue, orci quis ultricies ornare, ligula tortor ornare urna, sed fringilla turpis nulla ac sem. Nam nisi odio, consectetur nec nunc in, luctus pretium tellus. Suspendisse in leo elementum, rhoncus risus ut, blandit metus.
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In viverra urna vel turpis hendrerit, sed tincidunt dui fringilla. Proin mattis nisl nec mauris consequat congue. Praesent gravida eget dolor nec fermentum. Proin
finibus, magna elementum convallis viverra, leo nisi convallis magna, a condimentum nisl sem nec mauris. Sed ultricies lorem eu lectus tristique, sed ornare lorem auctor. Proin tincidunt enim dapibus nunc scelerisque, at consequat quam lobortis.
Nunc ornare lectus sit amet leo pharetra, at faucibus magna sodales. Cras auctor lacus lorem, ac porta libero feugiat vitae. Mauris metus velit, aliquam sit amet nunc eu, efficitur fermentum dolor. Suspendisse sed sagittis turpis, nec faucibus massa.
Fusce sagittis massa est, at sagittis est fermentum et. Curabitur egestas arcu eu neque elementum, sit amet sodales nibh viverra. Donec nec placerat nunc. Mauris non orci dapibus, porttitor leo quis, eleifend ante. Vivamus sed risus neque. Pellentesque
eget laoreet ante. Maecenas sed vehicula purus. Nam at sapien quis tortor vulputate tempor. Cras dignissim, metus sodales facilisis bibendum, dui erat faucibus elit, vel varius nisl lectus sed ante. Pellentesque ut magna consectetur est tempus vestibulum.
Maecenas fermentum metus nec accumsan volutpat. Mauris in viverra magna. Sed ante erat, blandit id fringilla eget, rhoncus at odio. Curabitur in metus nulla. Aliquam erat volutpat. Cras hendrerit augue massa, ullamcorper eleifend sapien ornare vel.</p>
</div>
</div>
CSS
html, body {
height: 100%;
}
html {
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
.header {
background:url("http://tympanus.net/Development/ArticleIntroEffects/img/7.jpg") center center no-repeat;
background-size:cover;
position:absolute;
left: 0;
top: 0;
width: 100%;
transform:translateY(0);
transition:1s cubic-bezier(0.215, 0.61, 0.355, 1) .2s;
opacity:1;
&.header--scrolled {
transform:translateY(-100%);
opacity:0;
transition:1s ease-in;
}
h1 {
position: absolute;
top:50%;
text-align: center;
transform:translateY(-50%);
width: 100%;
}
}
.subsection {
transition:.6s ease-out;
opacity:0;
transform:translateY(20px);
&.header--scrolled {
opacity:1;
transition:1s cubic-bezier(0.77, 0, 0.175, 1) .6s;
transform:translateY(0);
}
}
.subsection--inner {
max-width:800px;
padding:0 20px 60px 20px;
margin: 0 auto;
}
JQUERY
(function($, sr) {
var debounce = function(func, threshold, execAsap) {
var timeout;
return function debounced() {
var obj = this,
args = arguments;
function delayed() {
if (!execAsap)
func.apply(obj, args);
timeout = null;
};
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
}
// smartresize
jQuery.fn[sr] = function(fn) {
return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr);
};
})(jQuery, 'smartresize');
function intro() {
var topT = 0;
t = setInterval(function(){
if(topT==0){
window.scrollTo( 0, 0 );
}
},20)
var wh = window.innerHeight;
$(".header").css("height", wh);
$(".subsection").css("padding-top", (wh / 3 * 2));
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if(scroll == 0 && topT==0){
var header = $(".header");
var subsection = $(".subsection");
header.addClass("header--scrolled");
subsection.addClass("header--scrolled");
header.one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend',
function(e) {
topT=1;
});
}else if(scroll == 0 && topT==1){
$(".subsection").removeClass("header--scrolled");
$(".header").removeClass("header--scrolled");
topT=0;
}
});
};
intro();
$(window).smartresize(function() {
intro();
});
Getting rid of the hitch at the beginning
The CSS position attribute on the intro div needs to be set to fixed
Here's my example: http://codepen.io/internationalhouseofdonald/pen/aWWNqV
This script stops the user from scrolling when the page loads and then enables scrolling after 1000 milliseconds.
JavaScript
window.addEventListener("load", function() {
disableScroll();
});
setTimeout(function(){ enableScroll() }, 1000);
// left: 37, up: 38, right: 39, down: 40,
// spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36
var keys = {37: 1, 38: 1, 39: 1, 40: 1};
function preventDefault(e) {
e = e || window.event;
if (e.preventDefault)
e.preventDefault();
e.returnValue = false;
}
function preventDefaultForScrollKeys(e) {
if (keys[e.keyCode]) {
preventDefault(e);
return false;
}
}
function disableScroll() {
if (window.addEventListener) // older FF
window.addEventListener('DOMMouseScroll', preventDefault, false);
window.onwheel = preventDefault; // modern standard
window.onmousewheel = document.onmousewheel = preventDefault; // older browsers, IE
window.ontouchmove = preventDefault; // mobile
document.onkeydown = preventDefaultForScrollKeys;
}
function enableScroll() {
if (window.removeEventListener)
window.removeEventListener('DOMMouseScroll', preventDefault, false);
window.onmousewheel = document.onmousewheel = null;
window.onwheel = null;
window.ontouchmove = null;
document.onkeydown = null;
}
The only downside to this design is that if the user grabs the scrollbar (like I would on my Surface with my Surface Pen), the page would still scroll.

How to imitate fixed positioning on a <nav> element using jQuery?

I do not want to use normal fixed positioning because then the text below the nav bar will get pushed to the top, blocked by the nav bar itself. I am looking for an alternate method using jQuery that will keep the nav bar in the same position despite how much the window has scrolled.
My current code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
$('nav').on('scroll', function(e) { //Cancel the normal course of action for the nav bar
e.preventDefault();
});
var y = $('nav').offset().top;
$('nav').on('scroll', function() { //Continuously update top value to remain at top of window
var z = y + $(window).scrollTop();
$(nav).css("top", z + "px");
});
});
</script>
</head>
<body>
<nav>
<a>
Link1
</a>
<a>
Link2
</a>
</nav>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc, quis gravida magna mi a libero. Fusce vulputate eleifend sapien. Vestibulum purus quam, scelerisque ut, mollis sed, nonummy id, metus. Nullam accumsan lorem in dui. Cras ultricies mi eu turpis hendrerit fringilla. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In ac dui quis mi consectetuer lacinia. Nam pretium turpis et arcu. Duis arcu tortor, suscipit eget, imperdiet nec, imperdiet iaculis, ipsum. Sed aliquam ultrices mauris. Integer ante arcu, accumsan a, consectetuer eget, posuere ut, mauris. Praesent adipiscing. Phasellus ullamcorper ipsum rutrum nunc. Nunc nonummy metus. Vestibulum volutpat pretium libero. Cras id dui. Aenean ut eros et nisl sagittis vestibulum. Nullam nulla eros, ultricies sit amet, nonummy id, imperdiet feugiat, pede. Sed lectus. Donec mollis hendrerit risus.
</body>
</html>
All help will be appreciated.
You don't need the preventDefault part
The scroll event is triggered on window
Use variables
The nav needs a position:absolute
Here is a working fiddle: http://codepen.io/anon/pen/jPeQMp
$(function(){
var $window = $(window),
$nav = $('nav').css('position', 'absolute'),
initialTop = $nav.offset().top;
$window.on('scroll', function() {
$nav.css('top', initialTop + $window.scrollTop() + 'px');
});
});

How can I make the sidebar stop at a specific div while the user scrolls down?

I'm using this code to make the sidebar fixed at a certain div while the user scrolls down. The problem is that I have to manually enter in a threshold number and this isn't always ideal since the position of the section may change or be inconsistent across various browsers and systems. I'm wondering if there is a way I can automatically have the sidebar become fixed once the user scrolls down and .Section2 hits the top.
Fiddle
http://jsfiddle.net/EvAdP/6/
HTML
<header>
I'm the header
</header>
<div id="container">
<aside id="sidebar">
<div class="section1">I'm a sidebar section</div>
<div class="Section2">I'm another sidebar section</div>
</aside>
<section id="content">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis turpis turpis, dictum id sollicitudin eu, molestie ut tellus. Nam tincidunt mauris in erat vehicula adipiscing. Morbi cursus orci a nisl auctor nec porta eros consectetur. Vestibulum auctor congue mi, vitae molestie nisi faucibus vel. Ut et dui ut mauris posuere dignissim in et sapien. Duis a nulla ipsum. Duis accumsan porttitor justo at pretium. Aliquam quam urna, eleifend vitae consequat et, pharetra eu lectus. Etiam id magna mi. Donec pulvinar nibh in felis placerat condimentum consectetur enim iaculis. Integer et sapien justo, ac ullamcorper nisi. Praesent sed mauris non lacus pellentesque condimentum. Sed hendrerit consectetur nisi bibendum convallis. Pellentesque semper faucibus tortor malesuada dignissim.</p>
<p>Aliquam adipiscing commodo est, eu venenatis mi ullamcorper cursus. Integer vel magna in neque aliquet hendrerit. Mauris eros nisl, venenatis quis ultricies id, faucibus et mi. Nunc sit amet nulla odio. Phasellus quis eros id tortor imperdiet faucibus ac eu metus. Curabitur at feugiat dui. Vivamus imperdiet lectus id orci sodales sit amet eleifend ante tempus. Mauris vehicula elit eu dolor volutpat porttitor.</p>
<p>Praesent pretium convallis diam, sed faucibus dolor convallis eget. Pellentesque sollicitudin erat ac ligula viverra vel mollis diam tristique. Nulla tempus ligula ac dui fringilla consequat. Suspendisse accumsan volutpat semper. Morbi bibendum vehicula nibh id condimentum. Maecenas auctor mattis libero, ut suscipit tellus interdum quis. Nam eu dolor orci. Proin et tortor diam. Phasellus blandit leo ut elit faucibus varius. Donec condimentum congue lectus, sit amet gravida diam aliquet at.</p>
<p>Praesent eu libero sem. Phasellus elementum posuere velit, id aliquet ante elementum non. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus faucibus rutrum luctus. Suspendisse nec facilisis neque. Cras dui lacus, pellentesque at fermentum sollicitudin, aliquam et nisi. Proin eget sem diam, nec faucibus nulla. In nibh dolor, interdum at egestas a, dictum sed massa. Integer quis elit vitae enim lacinia tristique ac id purus. Pellentesque fermentum tempor sem sit amet venenatis. Nulla facilisi. Donec semper ultrices magna, posuere mattis turpis rhoncus ut.</p>
<p>Etiam porttitor erat sit amet odio egestas sit amet mollis magna convallis. Sed porttitor aliquet velit at placerat. Proin in turpis non velit gravida eleifend quis ac magna. Nunc sagittis, eros a pulvinar gravida, mauris urna viverra lorem, non posuere orci ligula vitae justo. Nulla neque erat, tempus at dapibus sit amet, scelerisque ac sapien. In in magna sapien, at auctor tellus. Donec nec turpis ligula, vitae scelerisque arcu.</p>
</section>
</div>
CSS
body {
margin:0;
}
header {
line-height:100px;
height:100px;
background-color:#F00;
}
#container {
position:relative;
}
#sidebar {
position:absolute;
background-color:#0F0;
}
#sidebar .section1 {
background: blue;
height: 150px;
width: 80px;
}
.Section2.fixed {
position:fixed;
top:0;
}
#sidebar .Section2 {
background: pink;
height: 150px;
width: 80px;
}
#sidebar.fixed {
position:fixed;
top:0;
}
#content {
margin-left:100px;
}
p:first-child {
margin-top:0;
}
JS
$(window).scroll(function () {
var threshold = 250;
if ($(window).scrollTop() >= threshold)
$('.Section2').addClass('fixed');
else
$('.Section2').removeClass('fixed');
});
Instead of specifying the threshold value try this
var threshold = $('.Section2').offset().top;
$(window).scroll(function () {
if ($(window).scrollTop() >= threshold)
$('.Section2').addClass('fixed');
else
$('.Section2').removeClass('fixed');
});
DEMO
Further to our discussions I thought I would post an alternative to the accepted solution that will work with flexible content.
It simply gets Section2 offset each time the scroll event is fired (but only if its not already .fixed):
EDIT: simply check that threshold is greater than zero:
var $Section2 = $('.Section2');
$(window).scroll(function () {
var threshold = $Section2.offset().top;
if (threshold>0 && $(window).scrollTop() >= threshold){
$Section2.addClass('fixed');
} else {
$Section2.removeClass('fixed');
}
});
DEMO

Categories