How do I synchronize the scroll position of two divs? - javascript

I want to have 2 divs sized to a particular width (i.e. 500px). One above the other aligned horizontally.
The top box should hide its scroll bar, the bottom should show a scroll bar and when the user scrolls I'd like the offset of the top box to change to the value of the bottom box. So that when the bottom DIV scrolls horizontally it appears that the top DIV is also scrolling in unison.
I'm happy to do this in Jquery if it makes the process easier.

$('#bottom').on('scroll', function () {
$('#top').scrollTop($(this).scrollTop());
});
Here we are using .scrollTop() for all it's worth, getting the scrollTop value from the element with scroll-bars, and setting the scrollTop for the other element to sync their scroll positions: http://api.jquery.com/scrollTop
This assumes that your bottom element has an ID of bottom and your top element has an ID of top.
You can hide the scroll-bars for the top element using CSS:
#top {
overflow : hidden;
}
Here is a demo: http://jsfiddle.net/sgcer/1884/
I suppose I've never really had a reason to do this, but it looks pretty cool in action.

I know this is an old thread, but maybe this will help someone.
In case if you need to synchronize scrolling in double direction, it's not good enough to just handle both containers' scrolling events and set the scroll value, because then scrolling events are getting into cycle and the scrolling is not smooth (try to scroll vertically by a mouse wheel an example given by Hightom).
Here is an example of how you can check if you are already synchronizing the scroll:
var isSyncingLeftScroll = false;
var isSyncingRightScroll = false;
var leftDiv = document.getElementById('left');
var rightDiv = document.getElementById('right');
leftDiv.onscroll = function() {
if (!isSyncingLeftScroll) {
isSyncingRightScroll = true;
rightDiv.scrollTop = this.scrollTop;
}
isSyncingLeftScroll = false;
}
rightDiv.onscroll = function() {
if (!isSyncingRightScroll) {
isSyncingLeftScroll = true;
leftDiv.scrollTop = this.scrollTop;
}
isSyncingRightScroll = false;
}
.container {
width: 200px;
height: 500px;
overflow-y: auto;
}
.leftContainer {
float: left;
}
.rightContainer {
float: right;
}
<div id="left" class="container leftContainer">
Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo. Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit, amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt, ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit, qui in ea voluptate velit esse, quam nihil molestiae consequatur, vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur? At vero eos et accusamus et iusto odio dignissimos ducimus, qui blanditiis praesentium voluptatum deleniti atque corrupti, quos dolores et quas molestias excepturi sint, obcaecati cupiditate non provident, similique sunt in culpa, qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio, cumque nihil impedit, quo minus id, quod maxime placeat, facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet, ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
</div>
<div id="right" class="container rightContainer">
Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo. Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit, amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt, ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit, qui in ea voluptate velit esse, quam nihil molestiae consequatur, vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur? At vero eos et accusamus et iusto odio dignissimos ducimus, qui blanditiis praesentium voluptatum deleniti atque corrupti, quos dolores et quas molestias excepturi sint, obcaecati cupiditate non provident, similique sunt in culpa, qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio, cumque nihil impedit, quo minus id, quod maxime placeat, facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet, ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
</div>
Here is the fiddle.

I've been looking for a double direction solution and thanks to you all, your contibutions helped me doing this :
$('#cells').on('scroll', function () {
$('#hours').scrollTop($(this).scrollTop());
$('#days').scrollLeft($(this).scrollLeft());});
See on JSFiddle : https://jsfiddle.net/sgcer/1274/
Hope it's help someone someday :-)

Alright, so I evaluated all of the options presented here, and they all had limitations of one form or another:
The accepted answer suffers from known issues using the mouse scroll wheel.
The next highest upvote does not have scroll wheel issues, but only works for two known elements. If you need more elements, it's not scalable.
The only solution that showed promise was Lacho's, but there were known element references in the code that were not included in the snippet. On the plus side, it had the structure needed for performance, and it's in TypeScript.
I leveraged that to create a reusable version that can work with an unlimited number of elements, and it doesn't require JQuery.
function scrollSync(selector) {
let active = null;
document.querySelectorAll(selector).forEach(function(element) {
element.addEventListener("mouseenter", function(e) {
active = e.target;
});
element.addEventListener("scroll", function(e) {
if (e.target !== active) return;
document.querySelectorAll(selector).forEach(function(target) {
if (active === target) return;
target.scrollTop = active.scrollTop;
target.scrollLeft = active.scrollLeft;
});
});
});
}
//RWM: Call the function on the elements you need synced.
scrollSync(".scrollSync");
You can check out the JSFiddle for this here: http://jsfiddle.net/gLa2ndur/3. You can see it uses both horizontal and vertical scrolling examples.
The only known limitation is that it might not work on divs of different sizes. I'm sure someone can work on incorporating Andrew's work into this if your use-case finds that necessary (mine does not).
I hope this is helpful to someone!

Another solution that prevents this looping problem and achieves a smooth scroll.
This makes sure that only the focused element gets the scroll event.
let activePre: HTMLPreElement = null;
document.querySelectorAll(".scrollable-pre").forEach(function(pre: HTMLPreElement) {
pre.addEventListener("mouseenter", function(e: MouseEvent) {
let pre = e.target as HTMLPreElement;
activePre = pre;
});
pre.addEventListener("scroll", function(e: MouseEvent) {
let pre = e.target as HTMLPreElement;
if (activePre !== pre) {
return;
}
if (pre !== versionBasePre) {
versionBasePre.scrollTop = pre.scrollTop;
versionBasePre.scrollLeft = pre.scrollLeft;
}
if (pre !== versionCurrentPre) {
versionCurrentPre.scrollTop = pre.scrollTop;
versionCurrentPre.scrollLeft = pre.scrollLeft;
}
});
});

Thanks to the answers above, I made a mixed solution that works preferentially for me:
var isLeftScrollTopCalled = false;
$('#leftElement').scroll(function (e) {
if (isRightScrollTopCalled) {
return isRightScrollTopCalled = false;
}
$('#rightElement').scrollTop($(this).scrollTop());
isLeftScrollTopCalled = true;
});
var isRightScrollTopCalled = false;
$('#rightElement').scroll(function (e) {
if (isLeftScrollTopCalled) {
return isLeftScrollTopCalled = false;
}
$('#leftElement').scrollTop($(this).scrollTop());
isRightScrollTopCalled = true;
});

I noticed that his question was pretty old, but I thought I could leave a jQuery implementation that works much better than using timers. Here, I am using two event listeners like the previously used solutions but, this will use proportions/percentage to sync scrolls for two differently sized div boxes. You can apply this same knowledge to get the position the scrollbars to a Vanilla JS solution. This will make the scrolling between the two divs much smoother.
/** Scroll sync between editor and preview **/
// Locks so that only one pane is in control of scroll sync
var eScroll = false;
var pScroll = false;
// Set the listener to scroll
this.edit.on('scroll', function() {
if(eScroll) { // Lock the editor pane
eScroll = false;
return;
}
pScroll = true; // Enable the preview scroll
// Set elements to variables
let current = self.edit.get(0);
let other = self.preview.get(0);
// Calculate the position of scroll position based on percentage
let percentage = current.scrollTop / (current.scrollHeight - current.offsetHeight);
// Set the scroll position on the other pane
other.scrollTop = percentage * (other.scrollHeight - other.offsetHeight);
});
this.preview.on('scroll', function() {
if(pScroll) { // Lock the preview pane
pScroll = false;
return;
}
eScroll = true; // Enable the editor scroll
// Set elements to variables
let current = self.preview.get(0);
let other = self.edit.get(0);
// Calculate the position of scroll position based on percentage
let percentage = current.scrollTop / (current.scrollHeight - current.offsetHeight);
// Set the scroll position on the other pane
other.scrollTop = percentage * (other.scrollHeight - other.offsetHeight);
});

Related

Scroll indicator of a single html element

I'm trying to create a scroll indicator regarding a single HTML element. In my page I have a paragraph with overflow set to "scroll".
Problem is, I tried many methods and each of them only seem to work on the "main" scroll event of the whole page.
Following is my adaptation of the code found at:
https://www.w3schools.com/howto/howto_js_scroll_indicator.asp
I assigned the class name "content" to my < p >.
<script>
window.body.getElementsByClassName("content").onscroll = function() {myFunction()};
function myFunction() {
var winScroll = document.body.getElementsByClassName("content").scrollTop || document.documentElement.scrollTop;
var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
var scrolled = (winScroll / height) * 100;
document.getElementById("myBar").style.width = scrolled + "%";
}
Gave this a shot to no avail, unfortunately.
That may be due to the fact I'm still learning.
Attached is also a preview of the current page.
As you can see, the grey scroll indicator is on top of it but it doesn't work when I scroll through the paragraph (< p >).
It may be quite simple but I can't figure this out.
<div class="header">
<div class="progress-container">
<div class="progress-bar" id="myBar"></div></div></div>
<a class="content">Lorem ipsum dolor sit amet, consectetur adipisci elit, sed do eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrum exercitationem ullamco laboriosam, nisi ut aliquid ex ea commodi consequatur. Duis aute irure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo. Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit, amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt, ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit, qui in ea voluptate velit esse, quam nihil molestiae consequatur, vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur? [33] At vero eos et accusamus et iusto odio dignissimos ducimus, qui blanditiis praesentium voluptatum deleniti atque corrupti, quos dolores et quas molestias excepturi sint, obcaecati cupiditate non provident, similique sunt in culpa, qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio, cumque nihil impedit, quo minus id, quod maxime placeat, facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet, ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.<br>
Thank you in advance!
So...
been manipulating my code a little bit.
This is what I found to work:
I assigned an id to my element, in this case "par".
I assigned " onscroll="myFunction()" " to my element.
(Optional) I assigned a class to style my element.
And then I inserted a javascript function inside my html file as a script (you can have a separate .js file, if you prefer so) with the following code. Keep in mind you must refer to your element with the same ID
< a class="content" onscroll="myFunction()" id="par">Your paragraph content < /a >
<script>
function myFunction() {
var winScroll = document.getElementById("par").scrollTop || document.getElementById("par").scrollTop;
var height = document.getElementById("par").scrollHeight - document.getElementById("par").clientHeight;
var scrolled = (winScroll / height) * 100;
document.getElementById("myBar").style.width = scrolled + "%";
}
</script>
Hope this will clear some doubts about my question. This may look uber-simple to some of you but it wasn't on my part. Have a nice day!

JS keeps redirecting me to a null page

I have this js script that will make the page fade in when the user enters, and fades out when the user clicks a link to another page. It works, but somehow I have my anchor links within the page and whenever I click the links, it takes me to the anchor and within a few seconds it redirects me to a null page like localhost/website/null
here's the code:
jQuery('body').css('display', 'none');
jQuery(document).ready(function() {
jQuery('body').fadeIn();
jQuery('a').on('click', function(event) {
var thetarget = this.getAttribute('target')
if (thetarget !="_blank" ) {
var thehref = this.getAttribute('href')
event.preventDefault();
jQuery('body').fadeOut(function(){
window.location = thehref
});
}
});
});
setTimeout(function() {
jQuery('body').fadeIn();
}, 1000)
I'm not understanding the problem -- maybe there isn't an issue? Refer to the snippet below?
Meta/Sidenote: SO needs a better way of creating snippets for comments -- this shouldn't be an answer, but there's no better way to supply a SO-generated demo.
jQuery('.container').css('display', 'none');
jQuery(document).ready(function($) {
var $container = $('container').fadeIn();
$('a').on('click', function(e) {
var _target = this.getAttribute('target');
if (_target != "_blank") { // (e.g., null, '_self')
var _href = this.getAttribute('href');
e.preventDefault();
$('.container').fadeOut(function() {
window.location = _href;
});
}
});
});
setTimeout(function() {
jQuery('.container').fadeIn();
}, 1000)
.container {
background: #09c;
padding: 1em;
height: 100%;
width: 100vw;
}
a:nth-child(2n)::after {
content: "\A";
white-space: pre;
}
body {
margin: 0;
padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="container">
_self (external link)
_self (internal link)
_blank (external link)
_blank (internal link)
No target (external link)
No target (internal link)
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Esse, reprehenderit, nostrum. Tempora totam, iusto, inventore cupiditate hic quam quas explicabo dolore mollitia eius ullam rerum minus placeat nobis in debitis magni non, dolor aut libero
dignissimos fugiat. Sed laboriosam itaque necessitatibus hic excepturi, perferendis, exercitationem cumque incidunt asperiores labore dolor.</p>
<p>Minus velit rerum, reiciendis perspiciatis pariatur accusamus, magni voluptatibus, voluptatem fugit optio libero quidem! Nostrum pariatur eveniet ipsum obcaecati aperiam deleniti hic quam facilis reprehenderit dolor ipsam suscipit, quidem laboriosam
impedit fugiat sit dignissimos delectus qui. Suscipit necessitatibus natus omnis eveniet molestiae nostrum aut culpa, tempora, voluptatibus modi eius nisi.</p>
<p>Illo quo, iure doloremque unde ullam iste. Fuga ullam dicta voluptate, odio sint molestiae expedita sequi, placeat omnis porro. Blanditiis ut, laboriosam nobis necessitatibus esse ipsam, magnam facilis in placeat delectus quidem eos laborum, illum
similique fugiat nesciunt doloremque ratione unde vel fugit excepturi dolor minima, amet tenetur. Tempora, eveniet.</p>
<p>Aliquam ex assumenda eum perspiciatis odio suscipit nemo in delectus. Iste in, ipsam iure deserunt, explicabo ipsum maxime. Praesentium, vitae, quos quia sed doloribus laboriosam. Architecto sapiente totam quisquam esse saepe asperiores provident
voluptatibus aperiam, similique sunt fugit cupiditate beatae aspernatur laborum, eius quas ab tempore consequatur officiis vero! Fugiat.</p>
<p>Explicabo minima necessitatibus soluta odio, sunt saepe aspernatur quasi molestiae cum? Nulla eveniet ad accusantium sed sapiente quod ea soluta repellendus culpa, ut deleniti dolore. Porro amet, quasi dignissimos provident modi nihil rerum quis explicabo,
voluptatem illo assumenda itaque. Maxime sequi asperiores enim tempora maiores dolor. Nihil quidem repudiandae asperiores!</p>
<p>Dicta facere at dolorum ut veritatis recusandae praesentium nesciunt illo, omnis doloremque labore repellendus soluta officia distinctio aperiam pariatur minus quia placeat enim, amet, quae repellat reiciendis nihil magni. Ad expedita dolores cupiditate
debitis dolore? Unde vitae inventore provident reiciendis adipisci dolorum ad ipsa possimus excepturi, mollitia nobis. Perspiciatis, voluptate.</p>
<p>Officia minima nulla delectus neque sapiente in voluptates iste facere dolorum sequi, animi fuga illo enim alias explicabo, culpa? Quaerat nesciunt animi, eius assumenda quidem sunt saepe nam suscipit voluptate eaque, laborum minus expedita nostrum
praesentium iusto eveniet officia ab tempore eos at. Dolores minus qui fugit, temporibus sequi tempora!</p>
<a id="foo" name="foo">ID:foo</a>
</div>
</body>

Two column layout. Scrolling anywhere on the page should scroll the right column

I have a two column website, however the user must focus in on the right column to scroll the main content. If the user is focused on the left-hand link bar nothing happens. I tried coding a script that will scroll the right column no matter where the user's mouse is. It does not feel natural and barely scrolls.
Here is my attempt: https://jsfiddle.net/knfg9Lqp/4/
Here is my website(scroll only works on right div): maxmastalerz.com
How could I go about making it non-laggy and fluid with the right amount of scroll?
I could probably use a plugin, however I'm leaning away from that idea.
$(document).bind('mousewheel', function(e){
var delta = (e.originalEvent.wheelDelta/120)*3;
var y = $('#right').scrollTop(); //your current y position on the page
$('#right').scrollTop(y-delta);
});
#left {
background-color: gray;
float: left;
width: 30%;
height: 150px;
}
#right {
background-color: aqua;
float: left;
width: 70%;
height: 150px;
overflow-y: scroll;
}
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<div id="left">
Link 1
Link 2
Link 3
</div>
<div id="right">
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"
</div>
TRY SCROLLING UP AND DOWN USING YOUR MOUSEWHEEL OR TOUCHPAD
Why are you dividing and multiplying? If you simply use var delta = e.originalEvent.wheelDelta; the scrolling looks right
https://jsfiddle.net/knfg9Lqp/5/

Cycling through elements with jQuery

I've got a little script to cycle forward and backward through some items. Here's a simplified pen which shows the same issue: http://codepen.io/2kp/pen/sLoEb
$(document).ready(function(){
var totalslides = $('p').length;
var currentslide;
var newslide;
$('.left').on('click', function() {
currentslide = $('p.active').index()+1;
if (currentslide == 1){
newslide = totalslides;
}
else {
newslide = currentslide-1;
}
$('p.active').removeClass('active');
$('p:nth-child('+newslide+')').addClass('active');
});
$('.right').on('click', function() {
currentslide = $('.slide.active').index()+1;
if (currentslide == totalslides){
newslide = 1;
}
else {
newslide = currentslide+1;
}
$('p.active').removeClass('active');
$('p:nth-child('+newslide+')').addClass('active');
});
});
The left button works fine, but the right button works just sometimes. On the real site, both left and right buttons work fine on everything except iPad. iPhone, Android and desktop are fine.
Really weird. Any help gratefully received.
Use .eq() instead of :nth-child. Also we can drop the need for an if block by using modulus (idea from this SO Answer):
$(function() {
var $slides = $('p.slide');
function transition(step) {
var $activeSlide = $('p.slide.active').removeClass('active');
var nextIndex = ($slides.index($activeSlide) + step) % $slides.length;
$slides.eq(nextIndex).addClass('active');
}
$('.left').on('click', $.proxy(transition, null, -1));
$('.right').on('click', $.proxy(transition, null, 1));
})();
button {
font-size: 32px;
}
.slide {
display: none;
}
.slide.active {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="left">☜</button> <button class="right">☞</button>
<div class="slides">
<p class="slide active">1: Lorem ipsum dolor sit amet, consectetur adipisicing elit. A alias neque necessitatibus, deleniti natus est dolores aut earum maiores ullam quas quis mollitia nemo, tenetur magni. Veniam in porro perspiciatis.</p>
<p class="slide">2: Itaque impedit ratione, eveniet, quisquam voluptate perferendis eum accusantium! Quia mollitia dolor a nulla, tenetur nesciunt ex tempore officia autem modi sit molestiae veniam voluptates vero itaque beatae similique quidem.</p>
<p class="slide">3: Est libero consequuntur ipsum distinctio corporis doloremque sunt iure autem tenetur labore at voluptate quam, repudiandae alias asperiores unde iste. Perspiciatis laborum, culpa sit maxime nostrum consequuntur labore reprehenderit adipisci.</p>
<p class="slide">4: Error eveniet, modi a sunt animi quos accusamus ullam quibusdam earum doloribus, omnis dicta ut. Facilis laboriosam autem libero itaque accusantium explicabo blanditiis veritatis sint nesciunt obcaecati, deleniti! Alias, impedit?</p>
<p class="slide">5: Modi neque harum vero minima nemo, dolor dolorum veritatis fuga obcaecati vitae! Quo commodi temporibus obcaecati rem repudiandae vel assumenda nostrum alias. Debitis non esse culpa officiis eum exercitationem distinctio!</p>
</div>
I'm not sure why. Probably some kind of conflict with other parts of my script, but replacing nth-child() with eq() and adjusting the maths sorted out the issue on the iPad.

onScroll event not firing else{} function

I'm trying to run a simple "onScroll do something" function.
When the visitor scrolls more than 20px away from the top window position the header is supposed to shrink down in size (along with it's content).
When the visitor scrolls back to the top (or <20px) the header is supposed to go back to it's original size (auto).
For some reason nothing I do seems to be working. The header (and the content) shrinks down fine, but the else{ } portion of the function does not fire. The header size does not change. It's like the size in the if{ } portion overrides everything else.
I just want to make a simple fixed header bar that shrinks (minimizes) once you scroll down the page and flips back to it's original size if you go back to the top.
I'd appreciate any help! Thanks a bunch!
HTML:
<header>
<img src="http://froggyadventures.com/wp-content/uploads/galleries/post-93/full/placeholder%20-%20Copy%20(3).gif" />
</header>
<section>
<p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.</p>
</section>
JS:
$(window).scroll(function () {
var topW = $(window).stop().scrollTop();
if (topW > 20) {
$('header').animate({"height": "15%"}),
$('header img').css({"height": "10%","width": "10%"});
} else {
$('header').animate("height", auto);
}
});
Demo Fiddle — http://jsfiddle.net/jwarddesign/NphFw/3/
I dont think it's possible to animate to "auto" height.
You could save the height before you're running the function, then you can animate it back to that height.
// Get the height
var h = $('header').outerHeight();
// Animate to the stored height
$('header').animate({"height": h})
http://jsfiddle.net/NphFw/22/

Categories

Resources