Fading Element on Scroll - javascript

I'm curious how I can create a DIV (or anything really) that I can fade (or change opacity of) when a user scrolls down the page. This DIV would sit at the top of the page, but only be clearly visible when at the very top of the page.
Additionally, it would be ideal if I I could have this element fade back in onmouseover, regardless of the current scrolled position on the page.

jQuery would allow for a succinct solution, whilst hiding most browser discrepancies. Here's a quick mock-up to get you started:
<script type="text/javascript">
//when the DOM has loaded
$(document).ready(function() {
//attach some code to the scroll event of the window object
//or whatever element(s) see http://docs.jquery.com/Selectors
$(window).scroll(function () {
var height = $('body').height();
var scrollTop = $('body').scrollTop();
var opacity = 1;
// do some math here, by placing some condition or formula
if(scrollTop > 400) {
opacity = 0.5;
}
//set the opacity of div id="someDivId"
$('#someDivId').css('opacity', opacity);
});
});
</script>
See also:
jQuery
Selectors
CSS
Events/Scroll
CSS/ScrollTop
CSS/ScrollLeft

I thought I would give it a go using the actual value of scrollTop to dictate the opacity level, thus getting a smooth fade. I also added the hover state for the second part. Thanks to David for refining the maths for me.
//reduce the opacity of the banner if the page is scrolled.
$(window).scroll(function () {
var height = $("body").height();
var scrollTop = $("body").scrollTop();
var opacity = 1;
if(scrollTop < 41)
{opacity = 1-Math.floor(scrollTop)/100;}
else
{opacity = 0.6;}
$("#header").css("opacity", opacity);
$("#header").hover(function(){
$(this).css("opacity", 1);
},function(){
$(this).css("opacity", 0.6);
});
});

Use scroll event, and analyse value of document.documentElement.scrollTop to set appropriated opacity.
http://www.quirksmode.org/dom/events/scroll.html

Related

Stop element from being fixed once scrolled past value

I have a fixed .widget element that remains visible at all times. Currently however, it scrolls over the footer area. My goal is to stop the widget before it hits the footer.
CSS
.widget {
position:fixed;
height:450px;
width:300px;
}
footer {
height:450px;
width:100%;
}
My route I'm taking is currently:
jQuery
var $bodyheight = $('body').height();
var $footerheight = $('footer').height();
var $widgetheight = $('.game_widget').height();
var $pageheight = $bodyheight - $footerheight - $widgetheight;
$(window).on('scroll', function() {
console.log($(this).scrollTop())
});
My next step would be to loop through to see if scrollTop > $pageheight then update some CSS.
Is this the best way of going about this? Is there a cleaner/simpler way to achieve the same result?
I have managed to solve this quite simply. Inside the scroll function I set 2 variables, one for the position of the fixed element, the other for the position of the footer. These return the exact value from how far the top of the element is from the top of the page. For the fixed element I need to know the distance to the bottom of this element so I also include the height.
var $fixedpos = $(".game_widget").offset().top + $('.game_widget').height();
var $footerpos = $("footer").offset().top - 25; // 25 accounts for margin
Using a simple if/else the CSS is updated to display none/initial depending on whether $fixedpos > $footerpos (i.e. the fixed element is overlapping the footer).
if ($fixedpos > $footerpos) {
$('.game_widget').css('display','none');
} else {
$('.game_widget').css('display','initial');
}
This works, however there is a 'flicking' effect as the fixed element overlaps the footer. This is due to the function executing extremely rapidly. The solution to the flicker is to use this simple 'throttling' plugin that adds a short delay (of your choice) between each execution of a function - http://benalman.com/projects/jquery-throttle-debounce-plugin/
You then just need to bind the on scroll function to the throttle:
function scrolling() {
console.log($(".game_widget").offset().top + $('.game_widget').height());
console.log($("footer").offset().top - 25);
var $fixedpos = $(".game_widget").offset().top + $('.game_widget').height();
var $footerpos = $("footer").offset().top - 25;
if ($fixedpos > $footerpos) {
$('.game_widget').css('display', 'none');
} else {
$('.game_widget').css('display', 'initial');
}
};
$(window).on('scroll', $.throttle(250, scrolling)); // 250ms between executing the function
});
This 250ms delay stops the function from executing so rapidly that the flickering effect occurs.
Hope this helps others trying to solve this problem.

How to have a div change opacity when scrolling? (Parallax)

I was wondering how to create something like a parallax scrolling effect. The farther you scroll down, the more opaque the div gets, and after a certain point, it starts getting more transparent again. I know JS/JQuery is required to do this. Can someone give me a simple way to achieve this?
you should use scrolltop and implement your own logic regarding the math and the div opacity will change as you scroll
this is the function: $(window).scrollTop()
I have created a fiddle for you to help: Basically you can listen for the scroll event, and control the css opacity property based on the direction.
var opc = 1;
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
changeOpacity(0, -0.1)
} else {
changeOpacity(1, +0.1)
}
lastScrollTop = st;
});
function changeOpacity (limit, amount) {
if(opc !== limit){
opc = opc + amount;
$('#content').css('opacity' , opc);
}
}
http://jsfiddle.net/Mvf67/1909/
Hope this helps!

Set divs opacity related to scroll position

I'm trying to set the opacity of a series of divs based on their individual proximity to scrollbar position.
This is what I have so far - http://jsfiddle.net/jGeYg/1/
I've managed to set the opacity to 0 when you are at the top of the window and it raise to 1 as you get to the top of div.
What I'm trying to acheive is for it not to start raising in opacity until you are 50px above the div and hit full opacity when you are at the top of the div. Essentially it's range where opacity changes is
$('div').position().top - 50 -> $('div').position().top //psuedo code
I don't want to use a plugin. I'm having trouble with the math rather than the code.
http://jsfiddle.net/b9ZCk/3/
I've added some debug text to show the position and opacity.
I am not sure if this is the desired effect that you want.. but try and let me know,
$(window).scroll(function() {
var st = $(this).scrollTop();
$('.block').each(function(index) {
if (($(this).offset().top-st) < 50) {
$(this).css({
'opacity': (0 + (st / $(this).offset().top))
});
} else {
$(this).css({'opacity': 0.1});
}
})
});
DEMO: http://jsfiddle.net/skram/jGeYg/5/

jQuery - How to get browser window to scroll horizontal when div is clicked?

I have picture of an arrow in a div. This div is fixed in the bottom right corner of very wide page.
How can I use jQuery to scroll the window right 600px each time the div is clicked? (And is it possible to detect when the page can no longer scroll right, and hide the arrow?)
Cheers.
Try something like this:
var distance = 600;
$("div").click(function() {
$("html:not(:animated), body:not(:animated)").animate(
{scrollLeft: "+="+distance}, 400
);
});
jsfiddle here: http://jsfiddle.net/juXLu/2/
[edit]
And here's detecting if you're at the end of the document http://jsfiddle.net/lukemartin/juXLu/5/
var distance = 600,
docWidth = $(document).width(),
scrollPos;
// click handler
$("div").click(function() {
// animate
$("html:not(:animated), body:not(:animated)").animate(
// amount to scroll
{scrollLeft: "+=" + distance},
// scroll speed (ms)
400,
// callback function
function(){
// check our scroll position
scrollPos = $(window).width() + $(window).scrollLeft();
// if it equals the doc width, we're at the end
if(docWidth === scrollPos) {
$("div").text("End of the line");
}
}
);
});
Use the jquery method scrollLeft
$(document).ready(function(){
$(window).scrollLeft((Number($(window).scrollLeft())+600)+'px');
});
Something like that :)
You could user the Scrollto plugin,
http://plugins.jquery.com/project/ScrollTo
It is really easy to use, just use the documentation. Then you could create a placeholder to determine whether or not its to the end of the page. Just stick the placeholder at the very end, and calculate the distance.

jQuery double animation using the jquery easing plugin

I want to implement something like this page does: link
Look at the Clicker box. The box has two animations going on. One for the easeInQuad, then the other animation is for the easeInOutSine.
How can I implement something like that in my own function?
$(function()
{
var iH = window.innerHeight + 80;
var position = $(window).scrollTop();
$(window).scroll(function()
{
var scroll = $(window).scrollTop();
if(scroll > position)
{
$("body").animate(
{
scrollTop: iH
},1000,
"easeInOutQuart")
.animate(
{
scrollTop: parseInt($(window).scrollTop()) - 80
},1000,
"easeInOutQuart");
}
else if(scroll < position)
{
$("body").get(0).scrollTop = 0;
}
position = $(window).scrollTop();
});
});
The second animate doesn't work quite well. But it does scroll it up. But it scroll it up too much not just 80 pixels. It scroll it up to the top, then the animation gets into an infinite loop. After the second .animate it will continue to animate it again and again and again. Non stop.
I think its better to use a toggle effect
http://www.sohtanaka.com/web-design/examples/toggle/
$("body").stop(true)
This will clear all animation Queues on the object.
http://docs.jquery.com/Effects/stop

Categories