To enhance the scroll effect, consider integrating CSS3 animation along with adjusting the position of the div as you scroll. This was not covered in previous responses:
$(window).scroll(function(){
var top = $(this).scrollTop();
if(top > 150){
document.getElementById("some_container_element").style.animationName = "specific_animation_name";
}
});
You can set initial css styles for some_container_element
using a different animation name than specific_animation_name
. The animation will only trigger when this style property changes based on the scroll position:
div.some_container_element {
background-color:rgb(140, 20, 20);
animation-name: another_animation;
}
... and define the animation specific_animation_name
, for example:
@keyframes specific_animation_name {
from {background-color:rgb(140, 20, 20);}
to {background-color:rgb(200, 20, 20);}
}
When dealing with div elements, it's often more effective to base the animation trigger on the distance of the element from the page top rather than the scroll position:
window.onscroll = function() {check_distance()};
function check_distance() {
var distance = document.getElementById("some_container_element").getBoundingClientRect().top;
if(distance < 600){ // distance threshold in pixels
document.getElementById("some_container_element").style.animationName = "specific_animation_name";
}
}
The conditional statement in the JavaScript function could also involve adjusting the div style properties to maintain the final state of the animation, such as:
...
document.getElementById("some_container_element").style.backgroundColor= "rgb(200, 20, 20);";