I have a div (#my-div
) and an element in it (#element
). The element is invisible at origin. I would like that when my-div
is on the screen, the element becomes visible and when we leave up or down, the element becomes invisible again.
I use a script and it works when I scroll first down up to my-div but when I scroll downer or I scroll upper, the element remains visible, no further animation happens.
I use CSS for the transition.
The HTML:
<section>
<div id="whatever">It is just a DIV</div>
<div id="my-div">My DIV
<div id="element" class="invisible">The element</div>
</div>
</section>
The CSS:
section {
width:100%;
min-height: 4000px;
text-align: center;
background-color: #e0e0e0;
}
#whatever {
width: 80%;
height: 500px;
margin: 10%;
background-color: #d0d0d0;
}
#my-div {width: 80%;
height: 300px;
margin: 10%;
background-color: grey;
}
#element {
width: 80%;
height: 100px;
background-color: red;
-webkit-transition: all 1500ms cubic-bezier(0.680, 0, 0.265, 1); /* older webkit */
-webkit-transition: all 1500ms cubic-bezier(0.680, -0.550, 0.265, 1.550);
-moz-transition: all 1500ms cubic-bezier(0.680, -0.550, 0.265, 1.550);
-ms-transition: all 1500ms cubic-bezier(0.680, -0.550, 0.265, 1.550);
-o-transition: all 1500ms cubic-bezier(0.680, -0.550, 0.265, 1.550);
transition: all 1500ms cubic-bezier(0.680, -0.550, 0.265, 1.550); /* easeInOutBack */
}
.invisible {
opacity: 0;
}
.visible {
opacity: 1;
}
The jQuery script:
$(window).scroll(function(){
if ($(window).scrollTop() <= $('#my-div').offset().top) {
$('#element').removeClass('invisible').addclass('visible');
}
if ($(window).scrollTop() > $('#my-div').offset().bottom) {
$('#element').removeClass('invisible').addclass('visible');
}
else {
$('#element').removeClass('visible').addclass('invisible');
}
});
The fiddle to see it live: http://jsfiddle.net/igorlaszlo/u0tzu02b/