bavavava bavavava - 3 months ago 8
CSS Question

Changing background image referred to each menu item only by scrolling

I'm developing a wordpress theme that has a function of changing background image by hovering menu item(each menu item is attached different image). On mobile, I'd like to change background image just by scrolling so that viewers don't need to click each menu to change the background image.

This is the method I implemented to change background by hovering.
http://codepen.io/nummelin/pen/kzaso

// When any of the a's 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]);
});


Achieving with scrolling, I think I need a function that hovering menu item by its position like the image below.

enter image description here

Does anyone have any ideas how to achieve this? I've been exploring a plugin or sample code similar to this, but haven't found any...
Any advices would be appreciated.

Answer

Okay, so this is the code I wrote. Hope it helps. I've worked on cross-fading effect but it wasn't that easy. If someone tried please teach me how to do it.

Demo on 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');
            }

        });
    });

});

});