bavavava bavavava - 4 months ago 14
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.

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

// Removes all previous classes but keeps sidebar1

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

// Applies the last part of the URL to sidebar1

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.


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:

  'use strict';


    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');

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


    $(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');