JQuery - process multiple instances of the same class separately?

Purpose:

  • I am trying to create a parallax scroll effect .

  • parallax-container is implemented like this: < div class="parallax slide-1" > < /div >

  • I need the parallax effect to start when its container scrolls into the view .

  • After leaving the show , the effect must be stopped.

Problem:

jQuery works great.

But: Since I can have several parallax containers on one page (for example, one at the top + one at the bottom), I need them to be processed independently by JQuery.

At the moment, the effect ...

  • 1.), ,
  • 2.) , .

.

, jQuerys.each(), .

, -, .

:

$(document).ready(function(){

$.fn.is_on_screen = function(){
    var win = $(window);
    var viewport = {
        top : win.scrollTop(),
        left : win.scrollLeft()
    };
    viewport.right = viewport.left + win.width();
    viewport.bottom = viewport.top + win.height();

    var bounds = this.offset();
    bounds.right = bounds.left + this.outerWidth();
    bounds.bottom = bounds.top + this.outerHeight();

    return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};

$(window).scroll(function(){ // Bind window scroll event
    if( $('.parallax').length > 0 ) { // Check if target element exists in DOM
        if( $('.parallax').is_on_screen() ) { // Check if target element is visible on screen after DOM loaded

            // ANIMATE PARALLAX EFFECT
            // If Parallax Element is scrolled into view do...

            // Variables
                var speed     = 2.5;
                var calc      = (-window.pageXOffset / speed) + "px " + (-window.pageYOffset / speed) + "px";
                var container = $(".parallax");

            // Function
                container.css({backgroundPosition: calc});

        } else {
            // ...otherwise do nothing
        }
    }
});

})
+4
1

, , , ( ..), .each . :

$(window).scroll(function(){ // Bind window scroll event
    $( ".parallax" ).each(function() {
        if( $( this ).is_on_screen() ) { // Check if target element is visible on screen after DOM loaded

            // ANIMATE PARALLAX EFFECT
            // If Parallax Element is scrolled into view do...
            // remember to replace ('.paralax') with (this)

            // Variables
                var speed     = 2.5;
                var calc      = (-window.pageXOffset / speed) + "px " + (-window.pageYOffset / speed) + "px";
                var container = $( this );

            // Function
                container.css({backgroundPosition: calc});

        } else {
            // ...otherwise do nothing
        }
    });
});
+3

Source: https://habr.com/ru/post/1545125/


All Articles