Fading in divs in html using javascript - javascript

In my project I want to fade in divs in html and I am using the following code
$(document).ready(function() {
/* Every time the window is scrolled ... */
$(window).scroll( function(){
/* Check the location of each desired element */
$('.hideme').each( function(i){
var bottom_of_object = $(this).offset().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
/* If the object is completely visible in the window, fade it it */
if( bottom_of_window > bottom_of_object ){
$(this).animate({'opacity':'1'},500);
}
});
});
});
#container {
height:2000px;
}
#container div {
margin:50px;
padding:50px;
background-color:lightgreen;
}
.hideme {
opacity:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/g/jquery.fullpage#2.5.9(jquery.fullPage.min.js+vendors/jquery.easings.min.js+vendors/jquery.slimscroll.min.js)"></script>
<link href="https://cdn.jsdelivr.net/jquery.fullpage/2.5.9/jquery.fullPage.min.css" rel="stylesheet" />
<div id="container">
<div>Hello</div>
<div>Hello</div>
<div>Hello</div>
<div>Hello</div>
<div>Hello</div>
<div>Hello</div>
<div class="hideme">Fade In</div>
<div class="hideme">Fade In</div>
<div class="hideme">Fade In</div>
<div class="hideme">Fade In</div>
<div class="hideme">Fade In</div>
</div>
which can be found at this JS Fiddle
In the project I also use the javascript code for
$(document).ready(function() {
$('#fullpage').fullpage();
});
which basically makes the scrolling better, details at https://github.com/alvarotrigo/fullPage.js/
The problem: Because of the full page code the fading in function does not enter the scroll if condition.

I think you're looking for something like this JS Fiddle 1
JS:
//initialize
var winHeight = $(window).height(),
sections = $('.sections'),
currentSlide = 0;
$('html, body').animate({scrollTop: 0}, 0);
//hide elements not in the view as the page load for the first time
sections.each(function() {
if ($(this).offset().top > winHeight - 5) {
$(this).fadeOut(0);
}
});
//show elements on scroll
$(window).scroll(function(event) {
// retrieve the window scroll position, and fade in the 2nd next section
// that its offset top value is less than the scroll
scrollPos = $(window).scrollTop();
if (scrollPos >= currentSlide * winHeight) {
nextSlide = currentSlide + 2;
$('#sec-' + nextSlide).fadeIn();
// as long as current slide is still in range of the number of sections
// we increase it by one.
if (currentSlide <= sections.length) {
currentSlide++;
}
}
});
----------
Update:
Upon a comment by the OP "I want the divs within sections to fade in on scroll not the section div but the ones inside it as there are multiple", all what we need to do is to change this line $(this).fadeOut(0); to this $(this).children().fadeOut(0); and then this line:
$('#sec-' + nextSlide).fadeIn(); to this $('#sec-' + nextSlide).children().fadeIn(1500);
and now, instead of the section itself, we're fading in and out all children of that section.
JS Fiddle 2

I'm surprised the previous answer got so many upvotes when the scroll event doesn't even get fired when using fullPage.js :D
The solution for your problem is detailed in the fullPage.js FAQs.
Which is basically using the fullPage.js option scrollbar:true or autoScrolling:false. This way the scroll event will get fired.
If you still want to use your fading effects when changing from one section to another, the proper solution is making use of fullPage.js callbacks or fullpage.js state classes to fire the animations. That can be done using javascript or plain css 3.
Check an example on how to use css3 animations in combination with the fullpage.js state classes on this video tutorial.

Related

Detecting end of scroll in a div

I have a dynamic website with many blog posts. I want to load just four posts at first and load another four when scrolled to end. I know how to handle it on the backend, but I am having problem on the frontend. I have set the height of html and body to 100%, due to which scroll events on the window didn't work. As a workaround, I decided to use a single div to detect the scroll. I added scroll event on the div, and it worked fine. But when I tried to detect the end of scroll on the div, the code executed at the beginning of the page load before performing any scrolls. The code I used is:
if (element.scrollHeight - element.scrollTop === element.clientHeight){
alert("End");
}
How do I make the alert to appear only after the div has been scrolled to the end instead at the begining?
You can use element.scrollTop + element.offsetHeight>= element.scrollHeight to detect scroll end.
Update:
Also adding a condition so that it won't fire when scrolling upwards.
For more on upward scroll condition,you can check this link.
const element = document.getElementById('element');
let lastScrollTop = 0;
element.onscroll = (e)=>{
if (element.scrollTop < lastScrollTop){
// upscroll
return;
}
lastScrollTop = element.scrollTop <= 0 ? 0 : element.scrollTop;
if (element.scrollTop + element.offsetHeight>= element.scrollHeight ){
console.log("End");
}
}
#element{
background:red;
max-height:300px;
overflow:scroll;
}
.item{
height:100px;
}
<div id="element">
<div class="item">item</div>
<div class="item">item</div>
<div class="item">item</div>
<div class="item">item</div>
<div class="item">item</div>
</div>
Answer for year 2023.
Now we have scrollend event.
Tested on chromium 108, firefox 109
Example:
const output = document.querySelector("p#output");
document.addEventListener("scrollend", (event) => {
output.innerHTML = `Document scrollend event fired!`;
});
According to mdn docs:
The scrollend event fires when the document view has completed scrolling.
Scrolling is considered completed when the scroll position has no more pending updates and
the user has completed their gesture.
Know more at mdn : Document: scrollend event
element.scrollTop + element.offsetHeight >= element.scrollTopMax
I mainly use this as a condition

How can I hide a button when scrolled to the top of a page?

I'm trying to adapt this JSFiddle to make the menu button on my website hide when I'm at the top of the page and show when I start scrolling down.
I modified the JS to match the CSS on my site. Then I placed it in tags in the head of my page
var $scb = $('<div class="toggle-menu-wrap"></div>');
$('.top-header').append($scb);
var $ccol = $('.content');
$ccol.scroll(function(){
$scb.stop(true,true).fadeTo(500, $ccol.scrollTop() > 10 ? 1 : 0);
});
However, it still doesn't work. Am I making a mistake in how I'm modifying the JS to fit my CSS?
You can include the toggle-menu-wrap element in your HTML from the start. There is no need to insert it using JS.
Write the one line of CSS you need, which is to hide the element from the beginning
.toggle-menu-wrap {
display: none;
}
Your version of jQuery uses 'jQuery' instead of '$' to reference itself. I would also re-write your JS like:
jQuery(document).ready(function() {
fadeMenuWrap();
jQuery(window).scroll(fadeMenuWrap);
});
function fadeMenuWrap() {
var scrollPos = window.pageYOffset || document.documentElement.scrollTop;
if (scrollPos > 300) {
jQuery('.toggle-menu-wrap').fadeIn(300);
} else {
jQuery('.toggle-menu-wrap').fadeOut(300);
}
}
Like #murli2308 said in the comments above, you need to attach a scroll event listener to the window:
$(document).ready(function () {
var $scb = $('<div class="scroll-border"></div>');
$('.above').append($scb);
var $ccol = $('.content');
$(window).scroll(function(){
$scb.stop(true,true).fadeTo(500, $ccol.scrollTop() > 10 ? 1 : 0);
});
})
Wrapping your code in $(document).ready() would also be a good idea.
The reason $ccol.scroll(function() { ... works in that fiddle is because of the CSS:
.content{
height: 200px;
width: 200px;
overflow: auto;
}
Notice overflow: auto;. This causes that specific div to be scrollable. However, on your website, you scroll the entire page, not $ccol. This means the event handler will never fire a scroll event (since $ccol will never scroll).
You might have forgotten to link Jquery.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
Link this inside your head tag incase.....
This should do the job:
$(window).scroll(function(e){
if ($(this).scrollTop() > 0) {
$(".your_element").css("display", "block");
} else {
$(".your_element").css("display", "none");
}
});

JQUERY- refer to specific div with class as other divs inside the html page

In the fiddle you will see at the center of the page a DIV that contains text next to an img.
When I scroll down/up I need to effect with jquery/javascript only the div who's the closest to the navbar-below. all the divs as the same class so I effect them all-not what I need
For example:
what I am trying to achieve : when I scroll down,the closest div to the navbar(yellow bar) will be painted(the div) green,so if I scroll down and the navbar "collapse" with the div with will paint in green, and when he passes him and "disapper" it will go back to original color and the next div will paint in green. is it possible?
Here's the JS FIDDLE
When I referred to div I meant this section :
<div class="x" id="inside_center">
<div class="left_side" id="left_inside_center">sddsadasasdsadLorem </div>
<div class="right_side" id="right_inside_center"><img src="http://img-9gag-lol.9cache.com/photo/a7KwPAr_460s.jpg"></div>
</div>
EDIT:
UPDATED JSFIDDLE :
http://jsfiddle.net/nnkekjsy/3/
I added my jquery,as you can see it works only for the first one,and then stuck.. i need to "pass" it along the others div below him when the are getting to the same point. any ideas? :
$(document).ready(function() {
$(window).scroll(function() {
var scrollVal = $(this).scrollTop();
var navHeight = $("#div_menu").outerHeight();
if ( scrollVal > 55) {
$('#left_inside_center').css({'position':'fixed','top' :navHeight+'px'});
} else {
$('#left_inside_center').css({'position':'static','top':'auto'});
}
});
});
Have you tried use the first-of-type to select the top div, if i understand what your trying to do.
CSS3 selector :first-of-type with class name?
An other solution would be to check the position of the div and the nav bar and pick the closest one.
$(".left_side").each(function () {
//compare scroll with div
if(window.scrollTop() = $(this).position.top())
{
//do something
}
});
I know the position and the scroll won't be the same value but you can play with the condition to put some range.
Edit :
I think this is what you want. The navHeight and the height variable should be outside the window.scroll function as they never change :
$(window).scroll(function() {
var scrollVal = $(this).scrollTop();
var navHeight = $("#div_menu").outerHeight();
var height = parseInt($(".right_side").css("height").split("px")[0]);
$(".left_side").css({'position':'static','top':'auto'});
$(".left_side").filter(function( ) {
return $(this).position().top - 10 < scrollVal && $(this).position().top + height > scrollVal;
}).css({'position':'fixed','top' :navHeight+'px'});
});
Working fiddle :
http://jsfiddle.net/nnkekjsy/6/

jQuery scrollTop to top of container div

I am using the excellent accordion menu provided by Ian Flynn of RocketMill: http://www.rocketmill.co.uk/create-accordian-boxes-with-a-rotating-arrow-using-css-jquery
This has worked well for me in the past, but I have a new client that leans towards the verbose. This presents a problem when the user attempts to click on their next desired accordion link. The accordion works correctly, but the hyperbolic amount of content shoots off of the page, presenting an obvious usability issue.
What I want to do is to reconcile the top of the active (just clicked on) "menuTitle" div with the top of its parent, the "content" div.
<div id="content">
<div class="menuTitle">
<strong>Title 1…</strong>
</div>
<div class="menuContent"> <!-- Sliding content box -->
<h5>Sub-title 1</h5>
<p>Content</p>
</div> <!-- End of div class="menuContent" -->
<!-- THE ABOVE SEVEN LINES REPEAT FOR EACH FOLD OF THE ACCORDION -->
</div> <!-- End of div id="content" -->
I have been working on this for about three days and have consulted many, many sites, jQuery guides, and whisky. I am not a jQuery expert. Please help!
Oh… I made a jsFiddle. My first: http://jsfiddle.net/Parapluie/CRXX8/
well, if i understand what you want..
http://jsfiddle.net/CRXX8/4/
$(document).ready(function() {
$('#content .menuTitle').on('click',function() {
$('#content .menuTitle').removeClass('on'); // "closes" the closing menu arrow
$('#content .menuContent').slideUp('normal'); // slide-closes the closing div
if($(this).next().is(':hidden') == true) {
$(this).addClass('on'); // "opens" the opening menu arrow
$(this).next().slideDown('normal',function(){
$('html,body').animate({scrollTop:$(this).prev().offset().top}, {queue: false,duration:250, easing: 'swing'}); // on complete slidedown, scroll the clicked .menuTitle to top of page
});// slide-opens the opening div
}
}); // end of click event
}); // end of ready
UPDATE:
As your called elements are wraped in a div called '#focusWide', you dont have to scrollTop html,body, you have to scrollTop the wraper div '#focusWide' and use position().top istead of offset().top. And i add more '11px' (half of wraper div padding).
$('#focusWide').animate({scrollTop:$(this).prev().position().top + 11 + 'px'}, {queue: false,duration:250, easing: 'swing'});
http://jsfiddle.net/CUu7h/2/
I use the function shown below, which works great in most cases. Just make sure the container/wrapper is scrollable (using overflow-y:auto). See fiddle
function scrollIntoView(oElement, sContainer, fnCallback) {
var oContainer, nContainerTop, nContainerBottom, nElemHeight, nElemTop, nElemBottom;
if (!oElement || oElement.length <= 0) {
return;
}
oContainer = (typeof sContainer == "object" ? sContainer : $(sContainer));
nContainerTop = oContainer.scrollTop();
nContainerBottom = nContainerTop + oContainer.height();
nElemHeight = oElement.height() || 25;
nElemTop = oElement[0].offsetTop - 50;
nElemBottom = nElemTop + nElemHeight + 100;
if ((nElemTop < nContainerTop) || (nElemHeight >= $(sContainer).height())) {
oContainer.animate({ scrollTop: nElemTop }, { duration: "fast", complete: fnCallback });
}
else if (nElemBottom > nContainerBottom) {
oContainer.animate({ scrollTop: (nElemBottom - $(sContainer).height()) }, { duration: "fast", complete: fnCallback });
}
else if (fnCallback) {
fnCallback();
}
}

Attach and detach affixed headers with Twitter Bootstrap

I'm trying to use the affix function to attach a header to the top of the screen, but have it attached only for a portion of the page. It should detach (and scroll up along with the content) when the user scrolls past a certain point.
I'm using the script from this jsfiddle.
What I'm trying right now is this:
$('#nav-wrapper').height($("#nav").height());
$('#nav').affix({
offset: $('#nav').position()
});
$('#nav').detached({
offset: $('#bottom').position()
});
With the .detached class like so:
.detached { position: static; }
Can't get this to work. Any suggestions?
Twitter Bootstrap affix module doesn't have that option. But, I've used many times hcSticky, it is awesome. Take a look, it's simply to use and works very well.
You can write the logic in a function, and pass it to affix as offset.top.
Try
var navHeight = $("#nav").height();
var detachTop = $("#detach").offset().top;
var navTop = $("#nav-wrapper").offset().top;
$('#nav-wrapper').height(navHeight);
$('#nav').affix({
offset : {
top : function() {
if ((navHeight + $(window).scrollTop()) > detachTop) {
return Number.MAX_VALUE;
}
return navTop;
}
}
});
Fiddle is here.
Another option which might work for you: http://jsfiddle.net/panchroma/5n9vw/
HTML
<div class="header" data-spy="affix">
affixed header, released after scrolling 100px
</div>
Javascript
$(document).ready(function(){
$(window).scroll(function(){
var y = $(window).scrollTop();
if( y > 100 ){
$(".header.affix").css({'position':'static'});
} else {
$(".header.affix").css({'position':'fixed'});
}
});
})
Good luck!

Categories