I am creating a website with few animation, below is the piece of javascript and css which is revealing image from left to right
var i = 0;
var interval = setInterval(function () {
$('.mask').width(i + "%");
i++;
if (i == 101) {
clearInterval(interval);
}
}, 20);
.mask {
background:white;
max-width: 640px;
z-index:1;
height: 426px;
position: relative;
overflow: hidden;
}
.img {
width: 100%;
position: absolute;
top: 0;
left: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mask">
<div class="img">
<img src="https://beebom-redkapmedia.netdna-ssl.com/wp-content/uploads/2016/01/Reverse-Image-Search-Engines-Apps-And-Its-Uses-2016.jpg" />
</div>
</div>
and then an javascript which reveals image from right to left.
var i = 0;
var interval = setInterval(function () {
$('.mask3').css({ left: -i + "%" });
i++;
if (i === 0) {
clearInterval(interval);
}
}, 20);
.wrapper {
width: 640px;
height: 430px;
position: relative;
}
.mask3 {
position: absolute;
top: 0;
left: 0;
background:white;
width: 100%;
height: 100%;
z-index:1;
}
.img {
width: 100%;
position: absolute;
top: 0;
left: 0;
z-index:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="mask3">
</div>
<div class="img">
<img src="https://beebom-redkapmedia.netdna-ssl.com/wp-content/uploads/2016/01/Reverse-Image-Search-Engines-Apps-And-Its-Uses-2016.jpg" />
</div>
</div>
Now I am trying to load this animation only when div is being displayed, or user scroll down to specific div, and then the animation shall roll back.
I tried few of the scripts, but all of them guided to use if else statement although I am not able to pick anything which is working, can someone please help me out on this one.
This is a very rough answer, but you can do this if you want. You will still need to work on your animation function more to make it hide and then display based on how you want it to be.
var elem = $('.img'); //use a better identifier like an id.
var counter = 0
elem.hide();
function myAnimation() {
elem.show();
var i = 0;
var interval = setInterval(function () {
$('.mask').width(i + "%");
i++;
if (i == 101) {
clearInterval(interval);
}
}, 20);
counter++;
}
$(window).scroll(function(){
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
if ((elemBottom <= docViewBottom) && (elemTop >= docViewTop) && counter < 1) {
myAnimation();
}
});
The counter is basically to animate it once, because you will trigger this animation on every scroll.
Related
I want to change the scroll direction at the middle of the page.
I tried to do it with "jInvertScroll", but this plugin increase left in css, like that:left: /* increase on scroll */ px ;
So if I want to change the scroll direction to the middle of the page, left will already have a value like:left: -1500px;
That's my problem.
Is there another way to do it?
HTML :
<div class="vertical"></div>
<div class="menu-change"></div>
<div class="horizontal">
<p>scroll</p>
</div>
CSS :
body {
overflow-x: hidden;
padding: 0;
margin: 0;
}
.scroll {
position: fixed;
bottom: 0;
left: 0;
}
.vertical {
width: 100vw;
height: 2500px;
background-image: url(https://source.unsplash.com/random);
}
.horizontal {
width: 8500px;
height: 100vh;
background-image: url(https://source.unsplash.com/random);
}
JS :
$(document).ready(function(){
var scroll_start = 0;
var startchange = $('.menu-change');
var offset = startchange.offset();
$(document).scroll(function() {
scroll_start = $(this).scrollTop();
if(scroll_start > offset.top) {
$('.horizontal').addClass('scroll');
var elem = $.jInvertScroll(['.scroll'],
{
onScroll: function(percent) {
console.log(percent);
}
});
$(window).resize(function() {
if ($(window).width() <= 0) {
elem.destroy();
}
else {
elem.reinitialize();
}
});
} else {
$('.horizontal').removeClass('scroll');
}
});
});
i am new learner of jquery and javaScript.
i want to create a slider with a big image section and a section of thumbs.
slider should slide automatically i have coded so far is working on click or hover but i dont know how to set it on auto please help me how to modify my code. code and slider screen shoot is given below.
slider image
$("document").ready(function()
{
$("#thumbs a").mouseenter(function()
{
var smallimgpath = $(this).attr("href");
$("#bigimage img").fadeOut(function()
{
$("#bigimage img").attr("src",smallimgpath);
$("#bigimage img").fadeIn();
});
return false;
});
});
</script>
#imagereplacement{
border: 1px solid red;
width:98%;
height:400px;
margin:auto;
padding-top:8px;
padding-left:10px;
}
#imagereplacement p{
text-align:inline;
}
#bigimage{
/* border: 1px solid green; */
margin:auto;
text-align:center;
float: left;
}
#thumbs{
/*border: 1px solid yellow;*/
margin: 110px 10px;
text-align:center;
width:29%;
float: right;
}
#thumbs img{
height:100px;
width:100px;
}
//This is where all the JQuery code will go
</head>
<body>
<div id="imagereplacement">
<p id="bigimage">
<img src="images/slider1.jpg">
</p>
<p id="thumbs">
<img src="images/slider1.jpg">
<img src="images/slider2.jpg">
<img src="images/slider3.jpg">
</p>
try with this example, please let me know in case of any more question from you :
$("document").ready(function(){
var pages = $('#container li'),
current = 0;
var currentPage, nextPage;
var timeoutID;
var buttonClicked = 0;
var handler1 = function() {
buttonClicked = 1;
$('#container .button').unbind('click');
currentPage = pages.eq(current);
if ($(this).hasClass('prevButton')) {
if (current <= 0)
current = pages.length - 1;
else
current = current - 1;
nextPage = pages.eq(current);
nextPage.css("marginLeft", -604);
nextPage.show();
nextPage.animate({
marginLeft: 0
}, 800, function() {
currentPage.hide();
});
currentPage.animate({
marginLeft: 604
}, 800, function() {
$('#container .button').bind('click', handler1);
});
} else {
if (current >= pages.length - 1)
current = 0;
else
current = current + 1;
nextPage = pages.eq(current);
nextPage.css("marginLeft", 604);
nextPage.show();
nextPage.animate({
marginLeft: 0
}, 800, function() {});
currentPage.animate({
marginLeft: -604
}, 800, function() {
currentPage.hide();
$('#container .button').bind('click', handler1);
});
}
}
var handler2 = function() {
if (buttonClicked == 0) {
$('#container .button').unbind('click');
currentPage = pages.eq(current);
if (current >= pages.length - 1)
current = 0;
else
current = current + 1;
nextPage = pages.eq(current);
nextPage.css("marginLeft", 604);
nextPage.show();
nextPage.animate({
marginLeft: 0
}, 800, function() {});
currentPage.animate({
marginLeft: -604
}, 800, function() {
currentPage.hide();
$('#container .button').bind('click', handler1);
});
timeoutID = setTimeout(function() {
handler2();
}, 4000);
}
}
$('#container .button').click(function() {
clearTimeout(timeoutID);
handler1();
});
timeoutID = setTimeout(function() {
handler2();
}, 4000);
});
* {
margin: 0;
padding: 0;
}
#container {
width: 604px;
height: 453px;
position: relative;
}
#container .prevButton {
height: 72px;
width: 68px;
position: absolute;
background: url('http://vietlandsoft.com/images/buttons.png') no-repeat;
top: 50%;
margin-top: -36px;
cursor: pointer;
z-index: 2000;
background-position: left top;
left: 0
}
#container .prevButton:hover {
background-position: left bottom;
left: 0;
}
#container .nextButton {
height: 72px;
width: 68px;
position: absolute;
background: url('http://vietlandsoft.com/images/buttons.png') no-repeat;
top: 50%;
margin-top: -36px;
cursor: pointer;
z-index: 2000;
background-position: right top;
right: 0
}
#container .nextButton:hover {
background-position: right bottom;
right: 0;
}
#container ul {
width: 604px;
height: 453px;
list-style: none outside none;
position: relative;
overflow: hidden;
}
#container li:first-child {
display: list-item;
position: absolute;
}
#container li {
position: absolute;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<center>
<h1>HTML Slideshow AutoPlay (Slide Left/Slide Right)</h1>
<br />
<br />
<div id="container">
<ul>
<li><img src="http://vietlandsoft.com/images/picture1.jpg" width="604" height="453" /></li>
<li><img src="http://vietlandsoft.com/images/picture2.jpg" width="604" height="453" /></li>
<li><img src="http://vietlandsoft.com/images/picture3.jpg" width="604" height="453" /></li>
</ul>
<span class="button prevButton"></span>
<span class="button nextButton"></span>
</div>
</center>
Here an example i've created that create an auto slider CodePen Demo and JSFiddle Demo
I've used an object literal pattern to create slide variable just to avoid creating many global function and variable. Inside document.ready i've initialised my slider just by calling slide.init({....}) this way it makes it easy to reuse and work like plugin.
$.extend(slide.config,option)
this code in simple words override you're default configuration defined in config key
as i mentioned in my above comment make a function slider() and place seTimeout(slide,1000) at bottom of your function before closing
Here in this code its done in animate key of slide object it is passed with two parameter cnt and all image array, If cnt is greater then image array length then cnt is set to 0 i.e if at first when cnt keeps on increment i fadeout all image so when i make it 0 the next time the fadeToggle acts as switch
if On then Off
if Off the On
and calling function slider after a delay makes it a recursive call its just one way for continuously looping there are many other ways i guess for looping continuous you can try
well i haven't check if all images Loaded or not which is most important in slider well that you could try on your own.
var slide = {
'config': {
'container': $('#slideX'),
'delay': 3000,
'fade': 'fast',
'easing': 'linear'
},
init: function(option) {
$.extend(slide.config, option);
var imag = slide.getImages();
slide.animate(0, imag);
},
animate: function(cnt, imag) {
if (cnt >= imag.length) {
cnt = 0;
}
imag.eq(cnt).fadeToggle(slide.config.fade, slide.config.easing);
setTimeout(function() {
slide.animate(++cnt, imag);
}, slide.config.delay);
},
getImages: function() {
return slide.config.container.find('img');
}
};
$(document).ready(function() {
slide.init({
'contianer': $('#slideX'),
'delay': 3000,
'fade': 'fast',
'easing': 'swing'
});
})
body {
margin: 0;
padding: 0;
}
.contianer {
width: 100%;
height: 100%;
position: relative;
}
.container > div,
.container > div >img {
width: 100%;
height: 100%;
position: absolute;
z-index: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container" id="slideX">
<div id="img1">
<img src="http://imgs.abduzeedo.com/files/articles/magical-animal-photography-gregory-colbert/5.jpg" />
</div>
<div id="img2">
<img src="http://cdn-5.webdesignmash.com/trial/wp-content/uploads/2010/10/great-dog-photography-016.jpg" />
</div>
<div id="img3">
<img src="http://onlybackground.com/wp-content/uploads/2014/01/marble-beautiful-photography-1920x1200.jpg" />
</div>
</div>
I am fairly new to writing in html, css, and coding in javascript.
I digress; i am trying to have an image of a gear rotate when the a user scrolls up and down the screen (i am hoping to give it an elevator effect when i add a belt).
I am using the jquery $(window).scroll(function(). I know it is working because when i use console.log("hi") it writes every time i scroll. My problem is the .animate() function that doesn't seem to work. I even tried downloading "http://jqueryrotate.com/" and using that to rotate.
Any help would be much appreciated!
## HTML ##
<div class="left_pulley">
<img src="gear2.png" />
</div>
<div class="right_pulley">
<img src="gear2.png" />
</div>
## CSS ##
.left_pulley
{
position: absolute;
margin: 0;
padding: 0;
top: 263px;
left: 87%;
height: 35px;
width: 35px;
}
.left_pulley img
{
width: 100%;
}
.right_pulley
{
position: absolute;
margin: 0;
padding: 0;
top: 263px;
left: 94.2%;
height: 35px;
width: 35px;
}
.right_pulley img
{
width: 100%;
}
## JS ##
First using .rotate({})
$(".left_pulley").rotate({bind:
$(window).scroll(function() {
if ($(this).scrollTop() > 0) {
$(.left_pulley).rotate({
angle: 0,
animateTo: 180,
})
})
})
})
Now using .animate({}) to try and just move it at all.
$(window).scroll(function() {
if ($(this).scrollTop() > 0) {
var scott = $('img');
scott.animate({
left: 180
}
}
});
$(window).scroll(function() {
if ($(this).scrollTop() > 0) {
var scott = $('img');
scott.animate({
left: 180
}
function() {
console.log("hi");
}
});
console.log("hi2");
}
});
.left_pulley {
position: absolute;
margin: 0;
padding: 0;
top: 263px;
left: 87%;
height: 35px;
width: 35px;
}
.left_pulley img {
width: 100%;
}
.right_pulley {
position: absolute;
margin: 0;
padding: 0;
top: 263px;
left: 94.2%;
height: 35px;
width: 35px;
}
.right_pulley img {
width: 100%;
}
<div class="left_pulley">
<img src="gear2.png" />
</div>
<div class="right_pulley">
<img src="gear2.png" />
</div>
[
picture of gears i want to rotate.
]1
You should look into the CSS3 transform property, more specifically the rotate() function. Here
It would also be beneficial to add a transistion property to create an animated 'tween' between rotation values. Here. Make sure to add this transition to the transition property (as this is where rotation is set).\
You can then change the rotation of the gear (with automatic animation!) using jquery by setting the css value of the transition property, for example:
#gear{
transition: transform 300ms;
transform: rotate(7deg);
transform-origin:90% 90%;
position:absolute;
left:100px;
top:100px;
font-size:10rem;
width:100px;
height:100px;
}
You can test it out here by hitting run.
https://jsfiddle.net/oc4hhons/
Borrowing heavily from https://stackoverflow.com/a/17348698/2026508
You could do something like this:
var degrees = 0;
var prevScroll = 0;
$(window).scroll(function() {
if ($(window).scrollTop() > 0) {
if (prevScroll > $(window).scrollTop()) {
$('.woo').css({
'-webkit-transform': 'rotate(' + degrees+++'deg)',
'-moz-transform': 'rotate(' + degrees+++'deg)',
'-ms-transform': 'rotate(' + degrees+++'deg)',
'transform': 'rotate(' + degrees+++'deg)'
});
console.log('prevScroll greater:', prevScroll)
} else if (prevScroll < $(window).scrollTop()) {
$('.woo').css({
'-webkit-transform': 'rotate(' + degrees--+'deg)',
'-moz-transform': 'rotate(' + degrees--+'deg)',
'-ms-transform': 'rotate(' + degrees--+'deg)',
'transform': 'rotate(' + degrees--+'deg)'
});
console.log('prevScroll less:', prevScroll)
}
prevScroll = $(window).scrollTop()
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height: 40px; width: 100px;background-image: url(' gear2.png ');background-color:blue;" class="woo">turn</div>
JS Fiddle-Updated, now they rotate together same direction but the rotation is depending on whether the scroll is up or down:
JS:
var $gears = $('.gear'),
$i = 0,
$scrollBefore = 0;
$(window).scroll(function () {
if($(this).scrollTop() > $scrollBefore){
$scrollBefore = $(this).scrollTop();
$gears.css("transform", "rotate(" + ($i+=4) + "deg)");
}else if($(this).scrollTop() < $scrollBefore){
$scrollBefore = $(this).scrollTop();
$gears.css("transform", "rotate(" + ($i-=4) + "deg)");
}
});
this JS Fiddle 2, makes them rotate in opposite directions, and each gear direction switches depending if the scrolling is up or down:
JS:
var $gearLeft = $('.left_pulley'),
$gearRight = $('.right_pulley'),
$i = 0,
$j = 0,
$scrollBefore = 0;
$(window).scroll(function() {
if ($(this).scrollTop() > $scrollBefore) {
$scrollBefore = $(this).scrollTop();
$gearLeft.css("transform", "rotate(" + ($i += 4) + "deg)");
$gearRight.css("transform", "rotate(" + ($j -= 4) + "deg)");
} else if ($(this).scrollTop() < $scrollBefore) {
$scrollBefore = $(this).scrollTop();
$gearLeft.css("transform", "rotate(" + ($i -= 4) + "deg)");
$gearRight.css("transform", "rotate(" + ($j += 4) + "deg)");
}
});
Thanks for all the help everyone!
Just want to post my finial code in case anyone else needs help in the future.
/* Scott Louzon 11/24/15
This code is used to rotate two images of a gears when user scrolls */
/*This function see's when user scrolls then calls rotate_right & rotate_left
accordingly */
var scroll_at = 0; //variable to keep track of
//scroll postion
$(window).scroll(function() {
if ($(this).scrollTop() > 0) //if scroll postion is not at
{ //top do this
if ($(this).scrollTop() > scroll_at) //if scroll postion is > than b4
{
rotate_down();
}
else if ($(this).scrollTop() < scroll_at) //if scroll postion is < than b4
{
rotate_up();
}
scroll_at = $(this).scrollTop(); //set varible to were scroll
//postion is at now
}
})
//Both these functions call css to rotate the image of a gear
var rotation = 0;
function rotate_down()
{
rotation+= 8;
$(".left_pulley").css("transform","rotate("+ rotation +"deg)");
$(".right_pulley").css("transform","rotate("+ (-1 * rotation) +"deg)");
}
function rotate_up()
{
rotation += 8;
$(".left_pulley").css("transform","rotate("+ (-1 * rotation)+"deg)");
$(".right_pulley").css("transform","rotate("+ rotation +"deg)");
}
.left_pulley
{
position: absolute;
margin: 0;
padding: 0;
/*Used for gear rotation */
transition: transform 1ms;
transform-origin:50% 50%;
top: 263px;
left: 87%;
height: 35px;
width: 35px;
}
.left_pulley img
{
width: 100%;
}
.right_pulley
{
position: absolute;
margin: 0;
padding: 0;
/* Used for gear rotation */
transition: transform 1ms;
transform-origin:50% 50%;
top: 263px;
left: 94.2%;
height: 35px;
width: 35px;
}
.right_pulley img
{
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="left_pulley">
<img src="gear2.png" />
</div>
<div class="right_pulley">
<img src="gear2.png" />
</div>
I was wondering if somebody could help me write a loop for this carousel? at the moment the carousel just scrolls to the right every 3 seconds then scrolls back to the left afterwards and resets itself, I would just like it to contiuously loop infinitly so it looks cleaner, could somebody point me in the right direction or help me? i know its simpler but i'm not much of a js developer! (this is for google sites html box otherwise i would have used a jquery plugin)
<style>
.carousel {
width: 1080px;
height: 220px;
position: relative;
overflow: hidden;
background-color:white;
margin-bottom: 20px;
margin-top: 20px;
margin-left: 70px;
}
.items {
width: 1080px;
position: absolute;
}
.items > div {
font-size: 20px;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.items > div > img {
padding: 10px;
}
.nav {
position: absolute;
bottom: 5px;
right: 15px;
}
.button {
cursor: pointer;
font-weight: bold;
color: #fff;
}
</style>
<div class="carousel" style="display:none;">
<div class="items">
<div>
<img src="http://i59.tinypic.com/etisye.png" border="0" alt="Alkamai Logo">
</div>
<div>
<img src="http://i59.tinypic.com/ouukxu.png" border="0" alt="AWS Logo">
</div>
<div>
<img src="http://i61.tinypic.com/16k3t43.png" border="0" alt="cover-it-live">
</div>
<div>
<img src="http://i60.tinypic.com/23wljxh.png" border="0" alt="escenic">
</div>
<div>
<img src="http://i58.tinypic.com/sbiqu1.png" border="0" alt="Livefire">
</div>
<div>
<img src="http://i58.tinypic.com/do9wep.jpg" border="0" alt="ooyala">
</div>
<div>
<img src="http://i61.tinypic.com/24werue.png" border="0" alt="varnish">
</div>
<div>
<img src="http://i60.tinypic.com/2ij14rd.png" border="0" alt="wordpress">
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"> </script>
<script>
var current_slide = 0; // zero-based
var slide_count = 4;
var slide_size = 1080;
var Direction = {
LEFT: -1,
RIGHT: 1
};
/**
* Moves to the next slide using the direction (dx) parameter.
*/
var nextSlide = function(dx) {
current_slide = (current_slide + slide_count + dx) % slide_count;
// Calculate the new value for css 'left' property and animate.
var left_offset = '-' + (current_slide * slide_size) + 'px';
$('.items').animate({'left': left_offset}, 1080);
};
$('.carousel').show();
setInterval(function(){
nextSlide(Direction.RIGHT);
}, 3000);
</script>
A slight modification to your current script can make it move forward continuously.
The changes are:
current_slide is always 1 (so as to always move forward only)
When we move .items X pixels to the left, we move the corresponding number of items to the end (the number that fits inside X pixels in width)
Updated Demo: http://jsfiddle.net/techfoobar/dWy9R/4/
Code:
var parent = $('.items');
var nextSlide = function (dx) {
// NOTE: always move forward only
current_slide = 1; //(current_slide + slide_count + dx) % slide_count;
// Calculate the new value for css 'left' property and animate.
var ileft_offset = current_slide * slide_size,
left_offset = '-' + ileft_offset + 'px',
iWidth = 0;
parent.animate({
'left': left_offset
}, 'slow', function() { // called when animation is done
iWidth = parent.find('> div:first').width();
while(ileft_offset > iWidth) {
parent.find('> div:first').appendTo(parent);
ileft_offset -= iWidth;
parent.css('left', '-' + ileft_offset + 'px');
}
});
};
A modified version that doesn't pause in between. Just goes on.
Demo: http://jsfiddle.net/techfoobar/dWy9R/5/
var nextSlide = function () {
parent.animate({
'left': '-' + slide_size + 'px'
}, 4000, 'linear', function() { // called when animation is done
var ileft_offset = slide_size,
iWidth = parent.find('> div:first').width();
while(ileft_offset > iWidth) {
parent.find('> div:first').appendTo(parent);
ileft_offset -= iWidth;
parent.css('left', '-' + ileft_offset + 'px');
iWidth = parent.find('> div:first').width();
}
nextSlide();
});
};
nextSlide(); // start it off!
I have a #sidebar (which starts below my #header div) and a #footer (around 120px off the bottom of the page).
I'm trying to make the sidebar scroll with the content of the page. The code below does this semi-successfully:
/* profile sidebar */
#sidebar>div{ width: 300px; margin-top: 10px; }
#sidebar.fixed>div{position:fixed;top:0;}
#sidebar.fixed_bottom>div{position:fixed;bottom:172px;}
jQuery(function ($) {
$.fn.scrollBottom = function() {
return $(document).height() - this.scrollTop() - this.height();
};
var el = $('#sidebar'),
pos = el.position().top;
$(window).scroll(function() {
if ($(this).scrollTop() >= pos) {
if ( $(this).scrollBottom() <= 172 ) {
el.removeClass('fixed');
el.addClass('fixed_bottom');
} else {
el.removeClass('fixed_bottom');
el.addClass('fixed');
}
} else {
el.removeClass('fixed');
}
});
});
The problem is, on smaller resolutions, this makes the sidebar "jump" once you reach a certain position on the page. It stops it from overlapping the footer (which is the problem if you remove the fixed_bottom class) but doesn't look good.
What I'd like to do is this: user scrolls to the bottom of the page, the sidebar scrolls along with the content until it reaches say 20px above the top of my footer, at which point it stays there until the user scrolls back up.
Thanks in advance,
I believe this should do what you want.
http://jsfiddle.net/FDv2J/3/
#sidebar>div{ width: 100px; margin-top: 10px; position:fixed; left: 0; top: 0;}
$(function() {
$.fn.scrollBottom = function() {
return $(document).height() - this.scrollTop() - this.height();
};
var $el = $('#sidebar>div');
var $window = $(window);
$window.bind("scroll resize", function() {
var gap = $window.height() - $el.height() - 10;
var visibleFoot = 172 - $window.scrollBottom();
var scrollTop = $window.scrollTop()
if(scrollTop < 172 + 10){
$el.css({
top: (172 - scrollTop) + "px",
bottom: "auto"
});
}else if (visibleFoot > gap) {
$el.css({
top: "auto",
bottom: visibleFoot + "px"
});
} else {
$el.css({
top: 0,
bottom: "auto"
});
}
});
});
I tried to break things up and name variables in such a way that it would be understandable. Let me know if there's anything you're unsure of. Notice that I added resize as well as scroll since it matters if the window changes size.
EDIT: Modified version using similar technique to the original to find the upper bound:
http://jsfiddle.net/FDv2J/4/
$(function() {
$.fn.scrollBottom = function() {
return $(document).height() - this.scrollTop() - this.height();
};
var $el = $('#sidebar>div');
var $window = $(window);
var top = $el.parent().position().top;
$window.bind("scroll resize", function() {
var gap = $window.height() - $el.height() - 10;
var visibleFoot = 172 - $window.scrollBottom();
var scrollTop = $window.scrollTop()
if (scrollTop < top + 10) {
$el.css({
top: (top - scrollTop) + "px",
bottom: "auto"
});
} else if (visibleFoot > gap) {
$el.css({
top: "auto",
bottom: visibleFoot + "px"
});
} else {
$el.css({
top: 0,
bottom: "auto"
});
}
}).scroll();
});
body{
margin: 0;
}
#sidebar>div {
width: 100px;
height: 300px;
margin-top: 10px;
background-color: blue;
position: fixed;
}
#stuff {
height: 1000px;
width: 300px;
background-image: url("http://placekitten.com/100/100")
}
#footer,
#header {
height: 172px;
width: 300px;
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="header"></div>
<div id="sidebar">
<div class="fixed">sidebar</div>
</div>
<div id="stuff">
</div>
<div id="footer">
</div>