Changing the background image applies to each menu item only by scrolling

I am developing a wordpress theme that has the function of changing the background image by hovering over a menu item (each menu item is attached to a different image). On a mobile device, I would like to change the background image by simply scrolling so that viewers do not need to click each menu to change the background image.

This is the method that I used to change the background by hanging. http://codepen.io/nummelin/pen/kzaso

// When any of the a inside of sidebarContainer are hovered
$( ".sidebarContainer a" ).hover(function() {

// Removes all previous classes but keeps sidebar1
$('.sidebar1').removeClass().addClass('sidebar1');

// Splits up the URL on the current href
var URI = $(this).attr('href').split('/');
console.log(URI[2]);

// Applies the last part of the URL to sidebar1 
$('.sidebar1').addClass(URI[2]);
});

Reaching the scroll, I think I need a function that hangs on a menu item by its position, as shown below.

enter image description here

Does anyone have any ideas how to achieve this? I studied a plugin or code sample like this, but did not find ... Any advice would be appreciated.

+4
1

, , . , . , . - , , , .

Codepen: http://codepen.io/bavavava/pen/rrNpaY

jQuery(function($){
  'use strict';

$(document).ready(function(){

    var elem = $('li.list-item'),
        $listPosition = $.map(elem, function(el, i) { return $(el).offset().top; }),
        $listURL = $.map(elem, function(el,i) { return $(el).find('a').attr('href'); }),
        $bg = $('.container');
        console.log($listPosition);
        console.log($listURL);

    //PRELOAD IMAGES
    $.fn.preload = function() {
        this.each(function(){
            $('<img/>')[0].src = this;
        });
    }

    $($listURL).preload();

    //SCROLL CHANGE
    $(window).on('scroll', function () {
        var windowScroll = $(this).scrollTop();

        $.each($listPosition, function (i, pos) {

            if (windowScroll >= pos) {
                $bg.css('background', 'url(' + $listURL[i] + '), black no-repeat center center fixed');
            }

        });
    });

});

});
0

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


All Articles